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.26.0 (#843)

Akshay Maloocd3bc887060e
diff --git a/evals/pcf/tests/capture-pcf-fixture.test.js b/evals/pcf/tests/capture-pcf-fixture.test.js
index 66c3077bc..ce46e48f6 100644
--- a/evals/pcf/tests/capture-pcf-fixture.test.js
+++ b/evals/pcf/tests/capture-pcf-fixture.test.js
@@ -22,7 +22,7 @@ function withDirs(fn) {
fs.mkdirSync(fixtures, { recursive: true });
return fn({ root, project, fixtures });
} finally {
- fs.rmSync(root, { recursive: true, force: true });
+ fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
}
@@ -76,7 +76,7 @@ test('does not delete a source directory named ..source when the destination is
);
assert.equal(fs.existsSync(marker), true);
} finally {
- fs.rmSync(root, { recursive: true, force: true });
+ fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
diff --git a/evals/pcf/tests/facts.test.js b/evals/pcf/tests/facts.test.js
index beb70569d..6ea339aa2 100644
--- a/evals/pcf/tests/facts.test.js
+++ b/evals/pcf/tests/facts.test.js
@@ -108,7 +108,7 @@ test('capture containment refuses outside targets before creating their parents'
assert.throws(() => assertInsideFixtures(outsideTarget, { fixturesRoot }), /Refusing to write outside/);
assert.equal(fs.existsSync(outsideParent), false, 'outside parent must not be created before refusal');
} finally {
- fs.rmSync(root, { recursive: true, force: true });
+ fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -120,7 +120,7 @@ test('capture containment refuses parent traversal targets', () => {
assert.throws(() => assertInsideFixtures(path.join(fixturesRoot, '..', 'escape'), { fixturesRoot }), /Refusing to write outside/);
} finally {
- fs.rmSync(root, { recursive: true, force: true });
+ fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -134,6 +134,6 @@ test('capture containment allows fixture-internal targets', () => {
assert.doesNotThrow(() => assertInsideFixtures(target, { fixturesRoot }));
assert.equal(fs.existsSync(fixturesRoot), true);
} finally {
- fs.rmSync(root, { recursive: true, force: true });
+ fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
diff --git a/evals/pcf/tests/reporter.test.js b/evals/pcf/tests/reporter.test.js
index 6b0f018e2..07cb48910 100644
--- a/evals/pcf/tests/reporter.test.js
+++ b/evals/pcf/tests/reporter.test.js
@@ -119,7 +119,7 @@ test('run-pcf.js reports a smoke case with no registered check, and one with no
assert.ok(lines.includes(`ok 3 - ${nameOf(smoke[2])}`), run.stdout);
assert.deepStrictEqual(lines.filter((line) => /^# (?:fixtures|unscored)/.test(line)), ['# fixtures 8 (pass 6, fail 0)', '# unscored fixtures 2']);
} finally {
- fs.rmSync(tmpRoot, { recursive: true, force: true });
+ fs.rmSync(tmpRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
diff --git a/evals/pcf/tests/run-pcf.test.js b/evals/pcf/tests/run-pcf.test.js
index f151c5601..46d8aa307 100644
--- a/evals/pcf/tests/run-pcf.test.js
+++ b/evals/pcf/tests/run-pcf.test.js
@@ -35,6 +35,6 @@ test('runner: exits non-zero when a contract expectation is deliberately broken'
assert.equal(code, 1, `stdout:\n${stdout}`);
assert.match(stdout, /PCF_INTENT_THIS_CODE_DOES_NOT_EXIST/);
} finally {
- fs.rmSync(tmpRoot, { recursive: true, force: true });
+ fs.rmSync(tmpRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.json
index eb0daba19..47f2a9f39 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.25.0",
+ "version": "2.26.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 eb0daba19..47f2a9f39 100644
--- a/plugins/model-apps/.plugin/plugin.json
+++ b/plugins/model-apps/.plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "model-apps",
- "version": "2.25.0",
+ "version": "2.26.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 b74fccece..1721f7c59 100644
--- a/plugins/model-apps/AGENTS.md
+++ b/plugins/model-apps/AGENTS.md
@@ -522,7 +522,15 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
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
+ unreadable. Before either scan that halts gives up on an unreadable app it takes the **whole scan** again, every app read
+ afresh, after 5 s, 10 s and 20 s (`rescanWhileUnreadable`): another build or maker changing an app leaves it unreadable for a
+ moment, and the build halted on that while the same build run minutes later passed. The answer is always the **last complete
+ scan**, never the apps read again merged into an older one: another app read before a wait can take the page in during it,
+ and a merged answer let the scan right before the first write in place pass it. So one that holds the page halts as
+ `pages-shared-across-apps`; one still unreadable after the last wait halts with the same words as before; a scan that fails
+ as a whole after a wait is waited out the same way, and the last one halts as a failed scan; and an app whose stored sitemap
+ is `malformed` is not waited for, since only an edit of that app changes it. A scan with nothing unreadable sends no extra
+ request. The report after the writes only warns, so it does not wait. A never-published app whose component read **succeeds** and finds **no sitemap component** is not yet shown to have no navigation: the
vendored SDK prefers a type-62 sitemap component on the app's **current** `appmoduleidunique` layer, but falls back to
`sitemapnameunique eq '<the app's unique name>'` when that component is absent and no other live app pins the candidate. So such an app may
hold a sitemap, and pages in it, that no component row links to it. `ensureSitemapInSolution` (sdk-build.js) still uses the naming convention
@@ -1714,6 +1722,122 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
lossy-download gate, the App Spec validation and, for `--include-managed`, the fragments file — a refusal
or a failed write before then leaves `pages/`, `app-spec.json` and the baseline as they were. A library
caller that omits `stagePages` still has `runDownload` write `pages/` itself.
+ **`app-spec.json` is checked with the tree, written after it.** Right after `stagedPages.check`, `main` runs
+ `assertFileReplaceable` (`lib/safe-fs.js`) on the spec: the refusals `writeFileSafe` would make at write
+ time (a link, a folder, a hard link — `UNSAFE_OUTPUT` — or a read-only file, `IO_ERROR` `read-only`), plus a
+ folder in which no new file can be made (`IO_ERROR` `folder-not-writable`, found by creating and removing an
+ empty `.app-spec.json.<pid>.<hex>.tmp`, since on Windows a folder's access list, not its mode, decides). That
+ probe is removed with the Windows lock retry; if it still cannot be removed, the look is refused too
+ (`IO_ERROR` `probe-not-removed`), and the error names the file and says it is an empty file the download made
+ that can be deleted. Any of them stops the download before the fragments file or `pages/` is written, and the
+ error ends "The download stopped before replacing anything". **Residual limit:** the spec is still written
+ after `pages/` is replaced, and the two are not one transaction. A write of the spec that fails for a reason
+ no look beforehand can see (a full disk, a lock taken meanwhile, a crash) comes after the page tree is
+ published. Its error keeps the write's code and says only what is known: the page tree was published, the
+ spec write reported an error, and whether `app-spec.json` matches those pages has not been confirmed —
+ resolve the error and run the same download again. It does not claim the spec is unchanged or mismatched
+ (an unchanged app's spec already matches; a rename can take effect and still report an error), nor that the
+ previous pages are gone (the swap keeps them when it cannot remove its folder, and warns). No copy of the
+ previous pages and no recovery folder is made.
+ **The managed download prints the not-round-tripped report after its restore** (`lib/managed-restore-report.js`):
+ with `--include-managed`, `main` also passes `deferReport`, so `runDownload` hands the report back as its parts
+ (`deferredReport`: the inventory and the membership notes) instead of printing it, and `main` recomputes it
+ (`notRoundTrippedReport`) less the ids a family restored (`subtractRestored`, by normalized id, never by name)
+ and prints it once. A plain download, and a library caller that does not ask, prints and answers the report
+ exactly as before. A family's omissions use one shape (`omission`: kind, id, key, name, a fixed `code` and its
+ fixed reason), never a service's own text. The source store is read, never written; its bytes are fingerprinted
+ before the first family reads it and again before `stagedPages.check`, and a store rewritten in between (a build
+ ran) stops the download with `managed-manifest-changed` before anything is written.
+ **The managed download restores the declared views a stable build created** (`lib/declared-view-io.js`,
+ `restoreManagedViews`). A view group exists only under `createIdentity: "stable-v1"`, so a restored view is
+ itself proof of that regime, and the download writes `createIdentity: "stable-v1"` and the floor with it. A
+ view comes back only when every check holds, in order: the group is settled and valid, its build created
+ (not adopted) the row, its publish is confirmed or not needed, the row is read with the table its
+ publication names, its projection hash equals the one the build proved, its saved and published layers are
+ equal (and equal the layer the build published), the inverse (`viewDeclarationFromLive`) can state the
+ query exactly (no aggregate, distinct, top, count, quick-find or unrepresentable filter, nested join or
+ related column it cannot bind), the key its table and name give is the bound key, the declaration compiles
+ back to the row part for part, the build's own planner (`planViewReconcile`, with the store record) answers
+ `noChange` and keeps the binding, and the spec still validates. The declaration carries `viewId` (the bound
+ id; environment-bound, like a dashboard's pinned id), `key` only when it is not `<table>/<name>`,
+ `activeOnly: false` and every condition the row holds (its `statecode` one included), so the rebuild
+ through the same store sends no write to the view's definition or to its solution membership. That is a
+ claim about the view, not the whole rebuild: the rebuild still runs every other step as for any spec (its
+ tables, forms and app are published, its sitemap written, its app components added). The view alone no
+ longer asks for its table's publish: a bound declared view the planner proves `noChange` with nothing
+ saved is not a reason to publish the table (`noteUnchangedManagedView` in `sdk-build.js`), while a form, a
+ chart written in the run, an owed publish or a changed or unbound view still asks for it. The row must
+ also still be in the app's solution (`solutionMembershipCheck` in `lib/managed-restore-report.js`): the
+ row itself or its whole table (root behaviour 0) counts; a table held without its subcomponents (behaviour
+ 1 or 2), or no membership at all, is `not-in-solution`, an unreadable one is `membership-unknown`, and the
+ download never adds or repairs one. The same holds for a chart.
+ Anything else is an omission with a fixed code
+ (`managedViews.omitted`), a WARNING, and the view stays in the not-round-tripped report.
+ **It restores the declared charts a stable build created the same way** (`lib/declared-chart-io.js`,
+ `restoreManagedCharts`), with two differences. A chart declaration has no id and no key field, so the
+ restored chart carries neither: the rebuild finds the row through the store's key (`<table>/<name>`),
+ which makes the restore an edit snapshot for that build folder (the store selects the exact row; a
+ same-named chart is never bound in its place). And the typed chart the SDK reads shows the category and
+ series but not the rest of the query, so the projection hash cannot prove the chart holds nothing more:
+ verify's own content checks (`chartContentChecks`) run on the PUBLISHED row against the declaration, and
+ every one must pass. A filter, a join, an order, a second series, a date grouping, a related category, a
+ measure that is not a count of the table's id, or an element the verifier does not model leaves the chart
+ out as `unsupported`; a renamed chart is `key-mismatch`. The declaration is the chart's table and name,
+ `reconcile: "declared"`, `chartType`, `groupBy`, the `measure` stated explicitly, and its description
+ and title when they hold text. Styling (palette, colours, axes, legend) is not the spec's: a rebuild
+ that writes nothing to the chart keeps it byte for byte. Omissions are `managedCharts.omitted`, each with a WARNING.
+ **It restores protected configuration** (`configurationIdentity: "stable-v1"`; `lib/declared-configuration-io.js`,
+ `restoreManagedConfiguration`). A configuration group keeps no declaration, so each one is rebuilt from the bound
+ rows as they are now, read IN MEMORY at their exact ids (`readConfigurationRow`), never through the SDK's cached
+ `fetchArtifact` (which writes current values, defaults and connection ids into workspace files). It is accepted
+ only when `restoreProofOf` (`lib/configuration-protected.js`) proves a rebuild of it changes nothing: the build's
+ own exact location, plan and judgment, every planned row matching a committed consumer row, and each such row's
+ current projection equal to the one the build committed (that comparison is what catches a row edited by hand,
+ since an omitted field plans as the row's own value), and the solution still holding it. Then the spec must
+ still validate. A declaration never carries a value, default, value schema, secret reference or connection: a
+ part left out is named in `withheld` (`fields`, never a value) and a NOTE, and is never written as a null (a
+ written null would clear it on a rebuild). Results: `managedEnvironmentVariables` (only when it says something,
+ so a store without configuration answers as before). A secret variable is `secret-withheld`; a data source whose
+ parent is not restored at exactly the row it names is `parent-unproven`; a second value row is
+ `multiple-values`; a required variable with neither a default nor a value (`restoreProofOf` answers only
+ flags, never the value) is `required-value-missing`, since its rebuild would stop as incomplete. Readiness and
+ the withheld parts (a default, a value schema, a value, a connection) are the flags `restoreProofOf` reads from
+ the rows it proved, in the same pass, never the earlier read the declaration came from: a default or a
+ connection removed between the two is judged as the proof saw it.
+ `managedConnectionReferences` restores a reference's logical name, connector and labels; its connection is
+ withheld (a rebuild without settings keeps it), a custom-connector reference is `unsupported-dependency`, and
+ one a page names is `page-unready` unless the gate's own verdict is `bound` (the build's page gate,
+ `configuration-build.js namedByPages` over `pagesStatingBindings`, would stop a rebuild before that page; a
+ plain download declares none). That verdict is `configuration-artifacts.js referenceBinding` (the build's
+ `observe`) over the environment's connections, read once per download through `list-connections.js
+ readConnections` and only for such a reference: a connection id in the row is not enough, the connection must
+ be listed and be one of the reference's connector, and an unreadable listing proves nothing.
+ `managedCustomApis` restores a scaffold API with both complete child lists, each child matched to the slot its
+ binding holds (`request:<unique name>` / `response:<unique name>`); one with `_plugintypeid_value` set is
+ `implemented`, one a page's `actionBindings` names is `page-unready` (CUSTOM_API_IMPLEMENTATION_UNPROVEN), and
+ other-language labels are withheld as `otherLanguageLabels` unless `RetrieveProvisionedLanguages` answers exactly
+ one language (read at most once per download, and not at all when no API gets that far).
+ `managedDuplicateDetectionRules` restores no rule: the family is withheld (`FAMILIES.duplicateRule.withheld`),
+ and every committed rule is omitted `state-unproven` without a read. A rule's status is part of its
+ declaration, but the committed root projection excludes state and the store keeps no rule state, so a rule
+ published or unpublished by hand reads exactly like one its build left that way; stating the current status
+ would make that change the spec's. Restoring a rule needs the store to commit the state its build proved. `tests/download-managed-configuration.test.js` builds through the real build command and
+ bundle, downloads through `main`, rebuilds over the same app folder with zero writes, downloads again byte for
+ byte, and scans every file and stream the download wrote for value, default, schema and secret canaries.
+ **Every download, plain or managed, reports the custom field security profiles it does not declare**
+ (`readFieldSecurityProfiles`). A profile is environment-wide security policy and no store family proves one is
+ this app's, so no restore declares one: `fieldSecurityProfiles[]` stays out of the spec, and a rebuild neither
+ changes nor recreates a profile (the secured columns still round-trip as `isSecured`;
+ `tests/download-managed-lifecycle.test.js` runs a download, its complete rebuild and a second download over a
+ custom and the System Administrator profile with permissions, users and teams, and checks none of them is
+ written or named beyond the custom profile's id and name). The read finds a
+ profile two ways, de-duplicated by id: solution component type 70 in the app's solution(s), and a
+ `fieldpermission` on a column the download emits as secured. It selects only the permission's profile id and
+ the profile's id and name, never a permission's bits or a profile's users and teams, and drops System
+ Administrator by its fixed id and by name. Each profile is named in one NOTE and in the result's
+ `fieldSecurityProfiles.omitted` (`omission`, code `ownership-unproven`); a failed read is a
+ `fieldSecurityProfiles` entry in `incomplete` with a fixed reason, never "no profiles". The list is not part
+ of the not-round-tripped report and never reaches `descriptionInventory`.
**The navigation titles are read in the language a rebuild of the spec resolves, and only in a language the
download knows**: `--language-code` (read as the build and verify read it), else the `languageCode` the spec
already on disk pins, else the environment's base language (one read through the download's own client,
@@ -2129,6 +2253,17 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
the build's reuse line makes): a rebuild never writes the content of a web resource that exists, so an edit that was not
recreated fails this check (`web-resource`), a spec content this machine cannot read (a missing `contentPath`, read relative to
the spec's folder) is `unverified`, and a run whose build skipped the web-resources phase reports it as phase-skipped.
+ Each **chart** is held to its definition, read from the published row (`lib/chart-verify.js`): its type (`chart-type`, the one
+ Series item's `ChartType`), the query it draws (`chart-data`: its table, one group-by column with no date grouping, one measure of
+ the primary id with the spec's aggregate — `count` and `countcolumn` are distinct — one category, one series, no filter and no
+ join), an explicit `description` (`chart-description`) and a declared chart's `title` (`chart-title`). A contradiction fails, a
+ legacy chart's as a declared one's (its message says a rebuild leaves a legacy chart as it is). What the verifier does not model —
+ an order, an outer join with nothing in it, an unknown element or attribute, a document type declaration, a malformed or oversized
+ document — is `unverified`, never dropped to obtain a pass; styling (palette, colours, axes, legends) is not compared. A declared
+ chart its managed bindings bind is read by its bound id: a namesake is never taken in its place, and a binding that is pending or
+ unusable makes the chart `unverified`. Two charts with the spec's name on its table are present, their content `unverified`. A
+ row read without its content columns (the eval's synthesized reader answers so) is checked for presence, and its type, its data
+ and a declared title are `unverified`, never passed; a declared description is still checked when the row carries one.
A relationship is verified by its **identity**, not its name: the answer has to state its schema name, its
type, both its tables and, for a 1:N, its lookup column — for an N:N, its intersect table and the column each
table has in it — and all of them have to match (`compareRelationship`, `lib/relationship-metadata.js`; an N:N's
@@ -2979,7 +3114,9 @@ charts phases. A spec that uses none of them takes the legacy paths unchanged. W
It is settled after the restore and the validation and before anything is published: `main` passes
`runDownload` `stagePages` (as it does for every download), which writes the page tree to a hidden staging
folder inside `<out>`, reads it back and answers `stagedPages` (`check`, `publish`); the tree, the spec and
- the baseline are written only after the fragments file, so a failure there leaves every output as it was. The
+ the baseline are written only after the fragments file, so a failure there leaves every output as it was (and
+ a tree or an `app-spec.json` that cannot be replaced is refused before the fragments file is written, with or
+ without generative pages). The
restored form is the group's `consumerState.declaration` (`DECLARATION_KEYS`, `autoSubgrids` included). A
plain download reads no form.
The download writes no store and transfers no binding authority: the first binding of a form from the
@@ -3832,6 +3969,7 @@ references/ ← Shared reference docs
agent-interaction-contract.md ← Agents are headless: no AskUserQuestion / plan mode inside a Task subagent; a declared tool is not always a delivered one (task tracking is optional)
data-caching.md ← Rule 15 on-mount fetch: de-dupe + cache (loaded conditionally)
localization.md ← Multi-language + RTL pattern (loaded conditionally)
+ promotion.md ← Promoting pages to another environment: managed or unmanaged, full solution or patch, version, dependency check, import order, rollback, what travels with a page (loaded only on a promote request)
supported-dependencies.md ← Versioned package list for generated pages
troubleshooting.md ← Deployment/runtime/env issues
verified-icons.txt ← ~5000 Fluent UI icon names; Grep-validated by page-builder
@@ -4034,7 +4172,7 @@ skills/
app-builder/
SKILL.md ← intent → model-driven app (create + edit)
genpage/
- SKILL.md ← Orchestrator skill (delegates to agents)
+ SKILL.md ← Orchestrator skill (delegates to agents); also the pull-to-repo mode (download pages without editing them)
edit-flow.md ← Edit flow steps (loaded only on edit path)
verify-flow.md ← Playwright browser verification (loaded only when user opts in)
report-issue/ ← Bug-report skill (bundled shared workflow)
@@ -4088,7 +4226,7 @@ Fluent UI V9 styles are Griffel's, and Griffel's runtime silently drops ten shor
The generative-page host renders a page inside a container of fixed height (the page root's parent is a host `FluentProvider` div with a definite height) and nothing above the page scrolls: every ancestor is `overflow: hidden` or `visible`, and the window does not scroll. So a page that does not establish its own scroll context shows only what fits, and everything below the fold is cut off with no scrollbar and no error (AB#6793599). The reported pages were flex columns with no bounded height; the rule that said otherwise lived only in the dark-mode section of `references/rules.md`. Live-verified on the host: a root with `height: "100%"` and `overflowY: "auto"` scrolls to its end; `overflowY` alone, `minHeight: "100%"`, and a two-div wrapper around a bare inner root all clip; a fixed header over a `flex: 1`, `minHeight: 0`, `overflowY: "auto"` body scrolls; and a content-box root with `height: "100%"` and 16 px of vertical padding scrolls but keeps its last 16 px below the visible area, which `boxSizing: "border-box"` fixes.
-- **The rule** (`scripts/lib/page-scroll.js`). It parses the page with the vendored TypeScript, follows the default export (through `memo`/`forwardRef`, an alias, an error-boundary class, a function declared below its `export default`, body components and components that render their `children` inside a box of their own) to the page's top element, and requires an element from there down that is bounded (a definite `height`/`maxHeight`, or a growing flex item in a bounded flex column with its automatic minimum removed) and scrolls (`overflowY` auto or scroll), with every element above it bounded. A percentage `height`/`maxHeight` is bounded only under a parent of *definite* height (a `height`, or a growing flex item of a definite column): a parent bounded by `maxHeight` alone bounds itself, but a `height: "100%"` child of it grows (CSS 2 §10.5). A `minHeight` that may be larger than the bound defeats it. One that is the same value as the bound (`calc()` included, whitespace aside) fits; two literals of the same unit (px, %, rem, em, vh) are compared within that unit, never converted, and a larger one fails; one the check cannot compare (px against a percentage or a rem, a token) is `scroll-context-unproven` with reason `min-height` (or the token's own reason). The alternatives of a condition (`a ? <X/> : <Y/>`, `a && <X/>`, a local component's arms, a `.map` callback's returns) are on screen one at a time, so each one that renders content must provide. One that renders nothing, or only recognised state views, is not judged: `Spinner`, `ProgressBar`, `Skeleton`, `MessageBar` and the Fluent text components (`Text`, `Body1`, `Caption1`, `Title1`, …), holding only text, values, their own parts (`MessageBarBody`, `SkeletonItem`, an action `Button`) and inline tags (`STATE_VIEWS` in the lib). Any other library or imported component in an alternative (a `Card` holding rows) is content whose layout the check cannot see, and is judged; one alternative that scrolls beside one that does not, or cannot be shown to, is `scroll-context-unproven` with reason `partial-alternatives`. It reads `makeStyles` slots (through `mergeClasses` and conditions) and inline styles; what it cannot read is `scroll-context-unproven` with a `reason`, never a pass. An element on that path that fills its container — its `height` or `maxHeight` is exactly `"100%"` or `calc(100% - N px)` with N smaller than its vertical padding in px, and its used height, `max(minHeight, min(height, maxHeight))` as CSS sizes it, is not provably smaller than the container by at least that padding (only `calc(100% - N px)` with N at least the padding proves it: `height: "100%"` under `maxHeight: "calc(100% - 64px)"` leaves room, but not under a looser `maxHeight: "150%"`, a fixed `maxHeight` the check cannot compare with the host, or with a `minHeight: "100%"` that wins over the maximum) — with vertical padding (any padding key that is not literally 0, a token or shorthand included) and no `boxSizing: "border-box"` is `scroll-context-padding`; `50%`, a calc() that leaves room for the padding or whose padding is a token, a box sized by flex or by a fixed length, and a scroll container in a flex column are not. That includes a bounded root that does not scroll around a scrolling body, because its padding pushes the body's end below the host in the same way (reasoned from the measurement, not measured).
+- **The rule** (`scripts/lib/page-scroll.js`). It parses the page with the vendored TypeScript, follows the default export (through `memo`/`forwardRef`, an alias, an error-boundary class, a function declared below its `export default`, body components and components that render their `children` inside a box of their own) to the page's top element, and requires an element from there down that is bounded (a definite `height`/`maxHeight`, or a growing flex item in a bounded flex column with its automatic minimum removed) and scrolls (`overflowY` auto or scroll), with every element above it bounded. A percentage `height`/`maxHeight` is bounded only under a parent of *definite* height (a `height`, or a growing flex item of a definite column): a parent bounded by `maxHeight` alone bounds itself, but a `height: "100%"` child of it grows (CSS 2 §10.5). A `minHeight` that may be larger than the bound defeats it. One that is the same value as the bound (`calc()` included, whitespace and the case of keywords, units and function names aside; but a value with a `var()`, an `env()`, an `attr()`, a CSS escape or a comment equals only the same text byte for byte, as custom property and environment variable names are case-sensitive (an `env()` name the host does not define takes its fallback), an `attr()` name may be, and escapes can spell any part of one, so `var(--height)` and `var(--HEIGHT)` are two values, `env(a, 0px)` and `env(A, 0px)` are not proven to be one, and another case or spacing of one value, `CALC(VAR(--h))`, is refused as unproven, which the remedy clears) fits; two literals of the same unit (px, %, rem, em, vh) are compared within that unit, never converted, and a larger one fails; one the check cannot compare (px against a percentage or a rem, a token) is `scroll-context-unproven` with reason `min-height` (or the token's own reason). The alternatives of a condition (`a ? <X/> : <Y/>`, `a && <X/>`, a local component's arms, a `.map` callback's returns) are on screen one at a time, so each one that renders content must provide. One that renders nothing, or only recognised state views, is not judged: `Spinner`, `ProgressBar`, `Skeleton`, `MessageBar` and the Fluent text components (`Text`, `Body1`, `Caption1`, `Title1`, …), holding only text, values, their own parts (`MessageBarBody`, `SkeletonItem`, an action `Button`) and inline tags (`STATE_VIEWS` in the lib). Any other library or imported component in an alternative (a `Card` holding rows) is content whose layout the check cannot see, and is judged; one alternative that scrolls beside one that does not, or cannot be shown to, is `scroll-context-unproven` with reason `partial-alternatives`. It reads `makeStyles` slots (through `mergeClasses` and conditions) and inline styles; what it cannot read is `scroll-context-unproven` with a `reason`, never a pass. An element on that path that fills its container — its `height` or `maxHeight` is exactly `"100%"` or `calc(100% - N px)` with N smaller than its vertical padding in px, and its used height, `max(minHeight, min(height, maxHeight))` as CSS sizes it, is not provably smaller than the container by at least that padding (only `calc(100% - N px)` with N at least the padding proves it: `height: "100%"` under `maxHeight: "calc(100% - 64px)"` leaves room, but not under a looser `maxHeight: "150%"`, a fixed `maxHeight` the check cannot compare with the host, or with a `minHeight: "100%"` that wins over the maximum) — with vertical padding (any padding key that is not literally 0, a token or shorthand included) and no `boxSizing: "border-box"` is `scroll-context-padding`; `50%`, a calc() that leaves room for the padding or whose padding is a token, a box sized by flex or by a fixed length, and a scroll container in a flex column are not. That includes a bounded root that does not scroll around a scrolling body, because its padding pushes the body's end below the host in the same way (reasoned from the measurement, not measured). Its message says the end of the page stays cut off, except where the other of `height` and `maxHeight` is a fixed length (`height: "100%"` under `maxHeight: "400px"`) and no `minHeight` other than auto or 0 is set: that box overhangs only a container shorter than that length plus the padding, so the message says the end may be cut off, and when (the box is refused all the same, as the host's height is not known to the check).
- **The remedy always works.** Each message gives one edit: `height: "100%"`, `overflowY: "auto"`, `boxSizing: "border-box"` (plus `minHeight: 0` when the element has a `minHeight` that may be larger than its container, or one the check cannot read) on the top element's `makeStyles` slot (with any overflow key in that slot deleted), or as the last keys of its inline `style`, made its last attribute, when its class cannot be read (an inline style wins over every class). For a library top element (`<Card>`), the edit wraps it in a `<div>` that has those keys. `page-scroll.test.js` applies the remedy to every shape the check rejects, including a template-string `className`, a spread of attributes and a `minHeight` that wins, and requires a pass. In a bounded flex column the message also advises `flexShrink: 0` on items that clip their own content: a Fluent `Card` is `overflow: hidden`, so it has no automatic minimum height and would be squeezed.
- **Who runs it.** `check-griffel-styles.js` runs it on every file with a default export, after the Griffel check. Its problems are appended to `problems` with exit 3, without the lib's internal `fix` object. The generation flows judge pages in full: `/genpage` 5b step 9 and 5c, the §7.5 fix when verification follows generation, and `/app-builder` Phase 1.5 step 5. The flows that change a page the run did not generate pass `--existing`: the `/genpage` edit flow (its Phase 5 check, and the §7.5 fix when verification follows an edit) and the `/app-builder` hand edit. There the problems go to `notes` and do not change `ok` or the exit code, and the flow tells the maker and offers the edit, applied only if they agree. The one exception: when the maker's requested edit itself rewrites the page's top-level layout, that layout is new code written in this run, so the agent applies the remedy as part of that edit and tells the maker in one sentence that it did. `edit-flow.md` and `verify-flow.md` §7.5 state this in the same words, and `genpage-dispatch-contract.test.js` pins both halves and that no note is applied without asking. If the scroll check itself throws — including when the vendored compiler is missing or corrupt — the CLI adds a `scroll-check-failed` note and leaves the Griffel result and exit code as they were; it never reports a silent clean result. The page-builder worker has no shell, so it gets the rule and a self-review. The Layer 2 eval grades every generated page with the same lib (`evals/model-apps/genpage/lib/scroll-context.js`); the pages captured before the rule are listed with their verdicts and report a skip.
- **Browser verification** (`skills/genpage/verify-flow.md` 7.2 and 7.4) cannot scroll the window or read the document's height, since neither moves in the host: it finds the element that scrolls and holds more than it shows, scrolls it to the end, and requires the last content's bottom to be at or above the lowest point the scroller and its clipping ancestors leave visible. Content inside a scroll region of its own (a list in a fixed-height panel) is left out of that measure; each such region is then scrolled to its own end and measured the same way, so a region that has not been scrolled is not taken for a cut-off page, and a padded region that overhangs its panel is still caught. With no scroller, content below the window is the clipping defect. `genpage-dispatch-contract.test.js` pins those scripts; they were run against an offline replica of the host (a bare root, the remedy, a padded content-box root, a short page, a root with a scrolling list and a footer, and a root with a padded list that overhangs its panel).
@@ -5441,6 +5579,18 @@ NODE20_BIN=/path/to/node20/bin node scripts/run-tests.js --with-sdk /path/to/sdk
workflow itself, across ubuntu × windows × macos and Node 20 × 22.
Keep `POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: "1"` on any new job that could run a
telemetry-emitting hook or script.
+- **A test that compares paths must accept the real name of a folder.** The product names an output folder
+ by its real path (`fs.realpathSync.native`), which is not always the path the test gave it: `os.tmpdir()` is
+ `/var/...` on macOS while its real path is `/private/var/...`, and on Windows CI it can be an 8.3 short name
+ (`C:\Users\RUNNER~1\...`). Canonicalize the expected path with `fs.realpathSync.native` first, or accept
+ either name (`download-model-app.test.js` checks both `out` and `fs.realpathSync.native(out)`); a plain
+ string compare passes on one runner and fails on another.
+- **Retry a test's own file moves on Windows.** When the test itself moves, removes or replaces a folder the
+ product has just written, an antivirus or indexer handle can refuse the call for a moment (EPERM, EACCES or
+ EBUSY). Wrap such test-own fs calls in the retry helper the download tests use (`hookRetry` in
+ `download-model-app.test.js`: Windows only, those three codes only, about 2 s), so the refusal does not
+ fail the test or escape into the product's own fs call. Never retry the product's call under test this way,
+ and keep every assertion as it is.
- The SDK's Jest suite needs **Node 20** (its `canvas` native module is built for the Node-20 ABI).
Set `NODE20_BIN` to a Node-20 bin dir; without it the SDK suite is skipped (plugin suite still runs).
- Evals: `node --test evals/model-apps/tests/*.test.js evals/model-apps/app-builder/tests/*.test.js
diff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.md
index 7404a817a..18aed8b93 100644
--- a/plugins/model-apps/CHANGELOG.md
+++ b/plugins/model-apps/CHANGELOG.md
@@ -5,6 +5,24 @@ All notable changes to the **model-apps** plugin.
Entries are deliberately short: what changed and why it matters to you. The reasoning,
evidence and trade-offs behind a change live in its PR, in `docs/`, or in the linked issue.
+## [2.26.0]
+
+- **Managed downloads restore more of an app:** declared views and charts, environment variables, connection references and Custom API scaffolds the binding store proves unchanged; values, defaults, secrets and connection ids are never written (#811).
+- The download names the field security profiles it leaves out, and `verify` holds a deployed chart's content to its definition.
+- A rebuild no longer republishes a table solely for a declared view the binding store proves unchanged in this run.
+- **Downloads:** an `app-spec.json` that cannot be replaced is refused before `pages/` or the fragments file is written; a later spec-write failure says only what is known.
+- **Page scroll check:** values with `var()`, `env()`, `attr()`, an escape or a comment compare byte for byte; the fixed-`maxHeight` padding message says when the end may be cut off (#840).
+- **Shared pages:** an app whose sitemap is briefly unreadable is read again, the whole scan repeated after each wait, before the build halts.
+- **Genpage:** a promotion guide, and a pull mode that brings existing pages into the project unedited (#675).
+
+### Limits
+
+- Secret environment variables, implemented Custom APIs, other-language Custom API labels and duplicate rules are not downloaded.
+- A connection reference a page names is downloaded only when the environment's connections can be listed and include its connection under its connector.
+- The browser verify step, keyboard scrolling and bare-text scrollers remain open (#840).
+- A publish refused because another customization is running still stops after the ordinary retries.
+- Duplicate rules made before opting in still cannot be adopted; migrating one is a separate replacement outside the plugin (#807).
+- Shared genpage manifests and opt-in page tests (#669, #670), the eval graders (#672, #674) and durable command-bar state (#812) are not in this release.
## [2.25.0]
- **Pages scroll:** the rules teach a bounded, scrolling page root; `check-griffel-styles.js` stops a generated page whose layout it can show would clip below the fold, or that it cannot read, with exit 3 and the fix (AB#6793599).
diff --git a/plugins/model-apps/docs/app-builder-capabilities.md b/plugins/model-apps/docs/app-builder-capabilities.md
index 5100de681..7a0f191f1 100644
--- a/plugins/model-apps/docs/app-builder-capabilities.md
+++ b/plugins/model-apps/docs/app-builder-capabilities.md
@@ -123,7 +123,8 @@ apart deliberately.
(the build warns). `--verify` fails on a missing spec column, filter condition or sort key (or
authored sort keys out of order), but not on extra deployed ones, so it cannot confirm a removal. Remove or reorder view columns in Maker, or
tear down and rebuild.
-- Choice-column charts.
+- Choice-column charts. `--verify` checks each chart's type, table, group-by column and measure (plus an
+ explicit description and a declared title), not only its name; a filter, join or second series fails.
### Custom grid rendering (preview) — ✅ SDK live-verified, environment-gated
- `entities[].columns[].visualization` — render a column as a `RadialDial`, `LineChart`, `HeatMap`
@@ -343,7 +344,7 @@ apart deliberately.
test here and by a `@jest-environment node` regression upstream.
### Edit flow (download → edit → rebuild) — ✅ verified live
-- `download-model-app.js` pulls a **deployed app** back into an editable App Spec (+ page code, icons, referenced entities, and the app's **real unmanaged solution** — `recoverAppSolution` enumerates the app's solution memberships and excludes the built-in `Active`/`Default`/`Basic` system solutions, so the spec names the right container for a later clean teardown); edit the spec and re-run the idempotent build — **create and edit share one path** (reuses app/tables, updates pages in place, keeps `GenPage` subareas). The app-shell phase **re-syncs the sitemap + components of any existing app** (fetch → recompute-from-spec → push → publish), so subarea add/rename/reorder edits land for **page-less apps too** — not just generative-page apps — and `--only app-shell` can force the rewrite. **Classic DashBoard subareas are *designed* to round-trip** — the dashboard is reconstructed into `dashboards[]` with **id-passthrough tiles** (each tile carries the deployed view/chart ids), so a rebuild recreates it against the existing views/charts without re-declaring them. **This now works end to end.** It previously did not: the vendored SDK’s `fetchArtifact(‘dashboard’, …)` threw `Cannot read properties of null (reading ‘length’)` while deserializing the `<parameters>` block it had itself serialized, so no tiles were recovered and the subarea was dropped — which failed the whole download unless `--allow-lossy-download` was passed. Root cause upstream: the grammar walk descended into **text** nodes, and the bundled XML parser returns `null` for a text node’s children. Fixed in the SDK and re-vendored; measured across the re-vendor as **0/4 → 4/4** round-trips (list tile, both chart-parameter spellings, and a tile with an empty parameter value), and pinned by `scripts/tests/dashboard-roundtrip.test.js`, which feeds a serialized dashboard straight back in. ([#478](https://github.com/microsoft/power-platform-skills/issues/478)) **Round-trip scope (not yet "complete"):** tables, relationships, sitemap/appShell, generative pages (code, prompt, data sources, model, and connector and Custom API bindings — `pages[].connectorBindings` / `pages[].actionBindings`, stated by an allowlist of the properties the references document, each with a value of a shape known to be safe, and only whole — a list holding a connection id, a credential or anything else is left out of the spec, reported by its place and never its value, and the page keeps it — which a rebuild writes into any environment; what they name is not carried: the download lists the connection references, Custom APIs and service resources another environment must already have, and a rebuild stops, before it writes anything, at a connection reference there that is for another connector), icons, dashboards, and solution round-trip; **forms, views, charts, and commands do NOT yet** — view hydration was tried and reverted (LIVE-verified the deployed savedquery set can't reliably distinguish author views from Dataverse's auto-generated Active/Inactive/QuickFind system views). All survive on the live app (a rebuild preserves them by discovery) but are absent from the downloaded spec, so edit them in Maker or a fresh spec. **Column types round-trip too, including Choice/MultiChoice** — their option sets are read per table, a local set becoming inline `options[]` (localizations preserved) and a shared one a `globalChoice` reference plus a `globalChoices[]` declaration; a column whose option set cannot be read is left untyped *and named*, and the App Spec cannot express option **values**, so a fresh rebuild re-bases them to `100000000 + index`. **File and Image columns** come back typed too — by their `AttributeTypeName` (FileType / ImageType), as both report `AttributeType` "Virtual", which an earlier release left out of every download without a word — with the `maxSizeKb` each was made with (left out when it is 10240 KB, the size a build gives a column that sets none) and, for an Image column the environment reports as the table's primary image, `isPrimaryImage: true` (a read of that detail that fails, or answers without a column, leaves the column typed without it, and the download says which read or column it was; the platform makes a table's first Image column its primary image whatever its create asks, so a rebuild into a fresh environment makes the spec's first Image column the primary image, whichever column carries the flag); the table's own image (`entityimage`) and the platform's companions of each column are not written, nor is the relationship the platform makes with each File or Image column (`FileAttachment_<table>_<column>` to `fileattachment`, `ImageDescriptor_<table>_<column>` to `imagedescriptor`) — the column brings it back, so it is neither carried in `relationships[]` nor warned about — and a column of any other type the App Spec cannot express is left out *and named*. **`relationships[]` are reconstructed** ([#567](https://github.com/microsoft/power-platform-skills/issues/567)): every custom 1:N whose parent is one of the app's tables or a stock table, and every custom N:N between two of the app's tables, each flagged `existing: true` (a teardown of the downloaded spec keeps it), with a deployed schema name kept whenever it is not the one the prefix would generate and a lookup label kept unless it is the default. One that `relationships[]` cannot express — a polymorphic lookup, a parent that is a custom table the app does not include (or whose metadata could not be read), an N:N to a table outside the app — is left out and *named* in the download's warnings and closing note: it stays on the deployed app, so a rebuild into the same environment leaves it alone, but a rebuild into a fresh environment does not create it.
+- `download-model-app.js` pulls a **deployed app** back into an editable App Spec (+ page code, icons, referenced entities, and the app's **real unmanaged solution** — `recoverAppSolution` enumerates the app's solution memberships and excludes the built-in `Active`/`Default`/`Basic` system solutions, so the spec names the right container for a later clean teardown); edit the spec and re-run the idempotent build — **create and edit share one path** (reuses app/tables, updates pages in place, keeps `GenPage` subareas). The app-shell phase **re-syncs the sitemap + components of any existing app** (fetch → recompute-from-spec → push → publish), so subarea add/rename/reorder edits land for **page-less apps too** — not just generative-page apps — and `--only app-shell` can force the rewrite. **Classic DashBoard subareas are *designed* to round-trip** — the dashboard is reconstructed into `dashboards[]` with **id-passthrough tiles** (each tile carries the deployed view/chart ids), so a rebuild recreates it against the existing views/charts without re-declaring them. **This now works end to end.** It previously did not: the vendored SDK’s `fetchArtifact(‘dashboard’, …)` threw `Cannot read properties of null (reading ‘length’)` while deserializing the `<parameters>` block it had itself serialized, so no tiles were recovered and the subarea was dropped — which failed the whole download unless `--allow-lossy-download` was passed. Root cause upstream: the grammar walk descended into **text** nodes, and the bundled XML parser returns `null` for a text node’s children. Fixed in the SDK and re-vendored; measured across the re-vendor as **0/4 → 4/4** round-trips (list tile, both chart-parameter spellings, and a tile with an empty parameter value), and pinned by `scripts/tests/dashboard-roundtrip.test.js`, which feeds a serialized dashboard straight back in. ([#478](https://github.com/microsoft/power-platform-skills/issues/478)) **Round-trip scope (not yet "complete"):** tables, relationships, sitemap/appShell, generative pages (code, prompt, data sources, model, and connector and Custom API bindings — `pages[].connectorBindings` / `pages[].actionBindings`, stated by an allowlist of the properties the references document, each with a value of a shape known to be safe, and only whole — a list holding a connection id, a credential or anything else is left out of the spec, reported by its place and never its value, and the page keeps it — which a rebuild writes into any environment; what they name is not carried: the download lists the connection references, Custom APIs and service resources another environment must already have, and a rebuild stops, before it writes anything, at a connection reference there that is for another connector), icons, dashboards, and solution round-trip; **forms, views, charts, and commands do NOT yet** — view hydration was tried and reverted (LIVE-verified the deployed savedquery set can't reliably distinguish author views from Dataverse's auto-generated Active/Inactive/QuickFind system views). All survive on the live app (a rebuild preserves them by discovery) but are absent from the downloaded spec, so edit them in Maker or a fresh spec. The exception is the managed download (`--include-managed --managed-manifest <store file>`): it brings back declared forms, dashboards, business rules and business process flows the store proves, and each declared view a `createIdentity: "stable-v1"` build created when the store proves it unchanged and the app's solution still holds it, so a rebuild from it writes nothing to the view while the rest of the rebuild (its publishes, sitemap and app components) runs as usual (with its environment-bound `viewId`; any other is named in `managedViews.omitted`), and each such declared chart whose published query a declaration states exactly and that the solution still holds (with no id: a rebuild through the same store binds it; any other is named in `managedCharts.omitted`), and, for an app built with `configurationIdentity: "stable-v1"`, each environment variable the store proves unchanged, without its value, default or value schema (any other is named in `managedEnvironmentVariables.omitted`), each such connection reference, without its connection (any other is named in `managedConnectionReferences.omitted`), and each such Custom API that has no implementation yet, with its complete parameters (any other is named in `managedCustomApis.omitted`); it never brings back a duplicate rule, since the store does not record the status its build left it in (each is named in `managedDuplicateDetectionRules.omitted`). **Column types round-trip too, including Choice/MultiChoice** — their option sets are read per table, a local set becoming inline `options[]` (localizations preserved) and a shared one a `globalChoice` reference plus a `globalChoices[]` declaration; a column whose option set cannot be read is left untyped *and named*, and the App Spec cannot express option **values**, so a fresh rebuild re-bases them to `100000000 + index`. **File and Image columns** come back typed too — by their `AttributeTypeName` (FileType / ImageType), as both report `AttributeType` "Virtual", which an earlier release left out of every download without a word — with the `maxSizeKb` each was made with (left out when it is 10240 KB, the size a build gives a column that sets none) and, for an Image column the environment reports as the table's primary image, `isPrimaryImage: true` (a read of that detail that fails, or answers without a column, leaves the column typed without it, and the download says which read or column it was; the platform makes a table's first Image column its primary image whatever its create asks, so a rebuild into a fresh environment makes the spec's first Image column the primary image, whichever column carries the flag); the table's own image (`entityimage`) and the platform's companions of each column are not written, nor is the relationship the platform makes with each File or Image column (`FileAttachment_<table>_<column>` to `fileattachment`, `ImageDescriptor_<table>_<column>` to `imagedescriptor`) — the column brings it back, so it is neither carried in `relationships[]` nor warned about — and a column of any other type the App Spec cannot express is left out *and named*. **`relationships[]` are reconstructed** ([#567](https://github.com/microsoft/power-platform-skills/issues/567)): every custom 1:N whose parent is one of the app's tables or a stock table, and every custom N:N between two of the app's tables, each flagged `existing: true` (a teardown of the downloaded spec keeps it), with a deployed schema name kept whenever it is not the one the prefix would generate and a lookup label kept unless it is the default. One that `relationships[]` cannot express — a polymorphic lookup, a parent that is a custom table the app does not include (or whose metadata could not be read), an N:N to a table outside the app — is left out and *named* in the download's warnings and closing note: it stays on the deployed app, so a rebuild into the same environment leaves it alone, but a rebuild into a fresh environment does not create it.
- **Crash-safe page tree.** A download stages the new `pages/` tree in a hidden folder and publishes it only after the download's checks and validation have passed (a lossy download without `--allow-lossy-download`, or an App Spec that fails validation, is refused first). Publishing writes the tree into a hidden swap folder beside `pages/`, checks that every page folder and file it wrote is still there (as a folder or a regular file, not a link), moves the previous tree aside, moves the new one in and removes the previous one last: a refusal or failure before then leaves `pages/` as it was and a failed move puts it back; when that is not possible, or the run stops between the two moves, the previous tree stays in the named hidden folder, which a later download reports. The spec is written after the pages are published, so a failed spec write leaves the new pages with the previous spec. Every operation in the download's own folders first checks the folder is still the one it made. Live-verified against 2.24.0: with folder creation denied in the output folder, and on a lossy-download refusal, 2.24.0 lost the maker's page edits and 2.25.0 kept `pages/` byte for byte. ([#814](https://github.com/microsoft/power-platform-skills/issues/814))
- **Portable schema (covered by offline real-bundle round trips):** downloads keep supported column format/length/range/precision options, Boolean labels, date format and AutoNumber masks; primary name length/mask; custom unmanaged Active/Inactive status reasons and alternate keys; solution/global-choice display names; and dashboard tile dimensions. Money numeric precision is retained only for `PrecisionSource: 2`, which the SDK always creates; effective precision still depends on the target transaction currency, so numeric equality is not currency equivalence. Column/organization-controlled and unknown sources are diagnosed with precision omitted, keeping the typed Money column and range. Status labels use the resolved authoring LCID, not the caller's UI language; a missing requested translation is diagnosed rather than substituted. An unavailable optional Keys collection loses no independent table, column or navigation metadata. Values equal to the SDK's create defaults are left implicit, except primary name lengths stay explicit so a fresh build can correct an environment that overrides the table create's length. An own-publisher unmanaged SVG table icon is captured with its `vectorIcon` reference and an `external: true` resource declaration, protecting a shared icon from teardown. Proven-equal status/key definitions and standalone Integer formats send no schema write on a same-environment rebuild; missing definitions and actual format edits still take the existing create/update path. Table icons retain their assignment and specific-table publish even when the saved name matches, so a failed publish can be completed on rerun. Inconclusive or malformed metadata is reported rather than treated as a known default.
- **Still outside that schema round trip:** script resources, raster/foreign/managed table icons, `roleGrants[]`, `sampleData`, Boolean defaults, column capabilities, BigInt ranges, DateTime behavior and unsupported/managed status reasons. Existing column length/range edits remain create-only; a downloaded dashboard still needs its source view/chart ids mapped, and its pinned `dashboardId` removed, before creating a separate dashboard in another environment. The new schema coverage is not a claim of full app cloning or new live verification.
diff --git a/plugins/model-apps/references/app-spec-schema-advanced.md b/plugins/model-apps/references/app-spec-schema-advanced.md
index f00c708c1..88c8b1b73 100644
--- a/plugins/model-apps/references/app-spec-schema-advanced.md
+++ b/plugins/model-apps/references/app-spec-schema-advanced.md
@@ -631,8 +631,11 @@ medical note, a national identifier, a private comment. Needs `minimumPluginVers
- **`--verify`** checks that each declared column is stored secured, that each profile holds exactly
its declared permissions, and that each named user and team holds the profile. These are metadata
reads made as the build's account; they do not prove what a user without the profile sees.
-- **Download** writes `isSecured: true` for a secured column. Profiles and their assignments are not
- downloaded.
+- **Download** writes `isSecured: true` for a secured column. Profiles, their permissions and their
+ assignments are not downloaded: a plain or managed download names each custom profile it finds (in the
+ app's solution, or holding a permission on a column it secures; never System Administrator) in a NOTE
+ and in its result's `fieldSecurityProfiles.omitted`, by id and name only. A rebuild of the downloaded spec
+ neither changes nor recreates a profile.
- **Teardown** never deletes a profile (users and teams can hold it beyond this app): it keeps each
declared profile, with its permissions and assignments, and names it as kept, by name only. Remove a
profile yourself once no one needs it.
@@ -747,6 +750,22 @@ spec's new columns.
list, in order (`quick-find <table>`); a stored search template such as `{0}%` is kept and verifies.
A changed list is written without any `--authorize` key: `overwrite:quickfind:<table>` approves only
replacing a local copy that differs from the server's (see Local copy below).
+- **Download.** A plain download leaves declared views out. With both `--include-managed` and
+ `--managed-manifest <store file>` (the build's `managed-bindings.<hash>.json`), each declared view a
+ `createIdentity` build created comes back in `views[]` with `reconcile: "declared"`, its `viewId`,
+ `activeOnly: false` and every condition it holds, when the store proves it unchanged since that build,
+ saved and published alike, and while the app's solution still holds it. A rebuild from it writes nothing to
+ the view; the rest of the rebuild runs as for any spec (its tables, forms and app are still published, its
+ sitemap written, its app components added). The download never adds a view to a solution. The spec gets `createIdentity: "stable-v1"`
+ with it. The `viewId` binds the view in that environment: remove it before building the spec elsewhere.
+ Any other declared view is left out, named with its reason in `managedViews.omitted` and in a warning,
+ and stays in the download's note. Each declared chart such a build created comes back in `charts[]` the
+ same way, as its table and name, `reconcile: "declared"`, `chartType`, `groupBy`, `measure`, and its
+ description and title when set; it carries no id, so only a build that uses the same store binds it (the
+ store names the exact row, never a same-named chart). A chart whose query holds anything a declaration
+ cannot say (a filter, a join, an order, a second series, a date grouping) or that was renamed is left out,
+ named in `managedCharts.omitted`; so is one the app's solution no longer holds. Its styling is not in the
+ spec; a rebuild that writes nothing to the chart keeps it.
**Approvals.** A view or chart that already exists and that this spec has not created in this run is
shown as an adoption: the build leaves it unchanged, builds the rest, and then stops naming the key —
@@ -912,7 +931,9 @@ are only added.
neither on it; the default and order checks of the table's plain forms are unchanged.
- **Download.** A plain download leaves declared forms out. To bring them back, pass both
`--include-managed` and `--managed-manifest <store file>`, the `managed-bindings.<hash>.json` file in the
- build's `.maker-workspace` for that environment and app. Each form the store proves comes back with
+ build's `.maker-workspace` for that environment and app. The download only reads that file: when a build
+ changes it while the download runs, the download stops with `managed-manifest-changed` and writes
+ nothing, so run it again. Each form the store proves comes back with
`reconcile: "declared"` and as it was declared (`autoSubgrids` and stated `false` flags included); a form
that is pending, gone or not valid is left out and named. A declared form with an event handler
(`events`) comes back with each handler library the spec does not declare, added to `webResources[]` as
@@ -1253,7 +1274,8 @@ Requires `minimumPluginVersion: "2.21.0"`. A flow without `reconcile` builds exa
## createIdentity (optional — stable create ids for declared views and charts)
Requires `minimumPluginVersion: "2.21.0"`. Write it on a **new** app only; never add it to an existing or
-downloaded spec. The only value is `"stable-v1"`; any other value is a validation error
+downloaded spec. A managed download writes it back itself, and only with the declared views and charts it
+restores (one the store proves this field's build created). The only value is `"stable-v1"`; any other value is a validation error
(`create-identity-invalid`), and a spec without the field builds exactly as before.
```jsonc
@@ -1320,7 +1342,8 @@ downloaded spec. The only value is `"stable-v1"`; any other value is a validatio
A page edit makes that check under the app's build and pages leases, so it is refused with
`build-locked` while a build of the app runs in the same workspace; run it again once the build ends.
- **`--verify`** reads each bound view or chart by its id. A binding whose create is not yet settled, or
- a file it cannot read, is reported as unverified, never as a pass.
+ a file it cannot read, is reported as unverified, never as a pass. A bound declared chart is checked at
+ its bound row only; a chart with the same name is never taken in its place.
## configurationIdentity (optional — exact ids for protected configuration)
@@ -1365,15 +1388,19 @@ the field builds exactly as before.
tokens adopt nothing and the next build prints new ones; if the row is deleted, the tokens are not used
and the item is created at its own id. A duplicate rule made before the opt-in is never adopted: its
stop stays exactly as before, and `adopt:duplicateRule:<key>` keeps its one meaning (the rule at its
- own reserved id, even when the key itself ends in what looks like `@<row id>`). Move that rule to its
- reserved id outside the plugin, or keep the app without the field.
+ own reserved id, even when the key itself ends in what looks like `@<row id>`).
Otherwise the stop says why the row cannot be adopted. A stop that names several such items lists the
tokens of each with its own id and field list. Several namesakes of one item stop as before, and the
plain `adopt:<kind>:<key>` token never selects a namesake. Plugin versions before this form refuse
the `@<row id>` tokens before anything is sent; after an adoption they bind an adopted row that has
no rows under it, and stop on one that has with `create-identity-unverified`. You can also keep the
- app without the field, or move it to the reserved ids outside the plugin. An app that already has
- protected bindings cannot go back: see "Removing the field" below.
+ app without the field, or move it to the reserved ids outside the plugin. For a duplicate rule,
+ moving to a reserved id means creating a separate replacement and arranging the cutover outside the
+ plugin; it is not an in-place id change. The plugin does not plan or perform that migration. Never
+ edit or reset the binding store to substitute ids. Leaving `configurationIdentity` absent is only for
+ an app that has not started keeping protected configuration bindings: do not remove it to bypass an
+ existing protected binding or a create still being settled. An app that already has protected
+ bindings cannot go back: see "Removing the field" below.
- **An uncertain lookup is not absence.** If the namesake lookup a first create needs cannot be read
completely (a failed read, a page that cannot be continued), the build stops with
`create-identity-unverified` and creates or binds nothing for that item. Restore access or reliable
@@ -1465,6 +1492,47 @@ the field builds exactly as before.
it again. The build command keeps these items' copies in a working folder of its own and removes it
when the command ends, so a copy kept after a failed send lasts until then: the stop applies within
that command, and the next command reads the server's rows afresh.
+- **Download.** A plain download writes none of these items. With both `--include-managed` and
+ `--managed-manifest <store file>`, each item the store holds is read again at its bound id and written
+ back into its list only when a rebuild of it through that store would change nothing: every bound row
+ still reads as the build committed it, the app's solution still holds it, and the spec still validates.
+ The restored spec gets `configurationIdentity: "stable-v1"` and a floor of at least
+ `minimumPluginVersion: "2.25.0"`. Anything else is left out with a fixed reason (`changed`, `missing`,
+ `unread`, `not-in-solution`, `pending`, …), a WARNING, and an entry in the result's `omitted`; a
+ restored item that leaves parts out names them, never their values, in a NOTE and the result's `withheld`.
+ A rebuild without `--deployment-settings` leaves those parts as they are.
+ - *Environment variables* (`managedEnvironmentVariables`): the schema name, type, name, description,
+ required flag and, for a data source, its connector, parameter key and a parent the download also
+ restores. The current value, `defaultValue` and `valueSchema` are never written (`withheld` names
+ them). A `secret` variable is left out (`secret-withheld`), as is a data source whose parent is not
+ restored (`parent-unproven`), a variable with more than one value row (`multiple-values`) and a
+ required variable with neither a default nor a value (`required-value-missing`: a rebuild of it would
+ stop as incomplete, and a download never fills one in).
+ - *Connection references* (`managedConnectionReferences`): the logical name, connector, name and
+ description. Which connection it is bound to is never written (`withheld` names `connection`, and
+ `connectionParameters` or `promptingBehavior` when the row sets them); a rebuild without settings
+ keeps the binding the row has. A reference to a custom connector is left out
+ (`unsupported-dependency`), and so is one a page of the app names unless the download proves it bound
+ as a rebuild's page gate does — its connection is among the environment's connections (read as
+ `list-connections.js` reads them) and is one of the reference's connector (`page-unready`):
+ declaring it would stop a rebuild before that page, which a plain download does not. No connection,
+ one of another connector, or connections that cannot be read all leave it out. A restored reference a
+ page names is gated like any declared one, so a rebuild stops before that page if its connection is
+ gone by then.
+ - *Custom APIs* (`managedCustomApis`): the unique name, labels, binding and bound table, flags,
+ allowed processing steps and execute privilege, with both child lists complete: each request
+ parameter's and response property's unique name, type, table, labels and (a request parameter's)
+ optional flag. Only a scaffold comes back: an API with a registered implementation (a plug-in type) is
+ left out (`implemented`), since the spec never declares one, and so is an API a page of the app calls
+ (`page-unready`): its rebuild would stop before that page until it had one. A child renamed, added or
+ deleted outside the plugin leaves the whole API out. Labels come back in the one language the row
+ answers in; on an environment with more than one language the others are not written (`withheld`
+ names `otherLanguageLabels`) and a rebuild leaves them as they are.
+ - *Duplicate rules* (`managedDuplicateDetectionRules`) are never brought back: each is left out
+ (`state-unproven`) without being read. A rule's status (published or unpublished) is part of what it
+ declares, and the store records its fields and conditions but not the status its build left it in, so a
+ rule published or unpublished by hand cannot be told from one its build left that way. The downloaded
+ spec declares no rule, and a rebuild of it leaves every rule as it is.
- **Unfinished work is checked first, declared or not.** Before its first service change, every build
reads the binding store for protected items whose create or edit has not finished. If the App Spec no
longer declares such an item, the build stops with `managed-settlement-pending` and sends nothing.
diff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.md
index edda843ea..94b170acb 100644
--- a/plugins/model-apps/references/app-spec-schema.md
+++ b/plugins/model-apps/references/app-spec-schema.md
@@ -845,7 +845,7 @@ list with "reach for it when…" guidance.
| `dashboards[].reconcile` | a declared dashboard (`reconcile: "declared"` on a global dashboard: the rebuild applies the spec's tiles by key and its description, adds new tiles, and keeps every tile the spec does not declare) |
| `businessRules[].reconcile` | a declared business rule (`reconcile: "declared"` on a rule: created Draft under an id the build keeps, then activated; managed and proved whole, with keyed conditions and actions, OR logic, default values, error messages and recommendations; an existing rule is adopted read-only, never edited) |
| `businessProcessFlows[].reconcile` | a declared business process flow (`reconcile: "declared"` on a flow, with a `key` on every stage and step: created Draft with ids the build keeps, then activated; managed and proved whole, so a rename keeps a stage's or step's id; an existing flow is adopted read-only, never edited, and a removed or reordered stage or step is refused) |
-| `createIdentity` | stable create ids for declared views and charts, on a new app only (`createIdentity: "stable-v1"`) |
+| `createIdentity` | stable create ids for declared views and charts, on a new app only (`createIdentity: "stable-v1"`; a managed download writes it back with the declared views and charts it restores) |
| `configurationIdentity` | exact ids and a binding store for declared environment variables, connection references, Custom APIs and duplicate rules (`configurationIdentity: "stable-v1"`, `minimumPluginVersion: "2.23.0"`): a duplicate rule is created and then only verified, and a Custom API takes only single-request or create-only edits |
| `columns[].dateTimeBehavior` | portable schema: calendar-day dates, fixed option values (`{ "value", "label" }`), table search and duplicate detection (`searchEnabled` / `changeTrackingEnabled` / `duplicateDetectionEnabled`) |
@@ -1077,6 +1077,11 @@ why they need naming here at all.
"description": "Where the open workload is concentrated." }
```
- `chartType`: `Column · Bar · Pie · Line`. **`groupBy` MUST be a Choice column** on `entity`.
+- `--verify` checks the deployed chart, not only its name: its type, its table, its group-by column and
+ its measure must match the spec, and it must have no filter, join or second series. An explicit
+ `description`, and the `title` of a declared chart, must match too. A mismatch fails. A rebuild does
+ not change an existing chart unless it has `reconcile: "declared"`, so declare it or recreate it.
+ Parts of a chart that verify cannot read are reported as unverified. Styling is not checked.
## forms[]
```jsonc
@@ -1904,6 +1909,8 @@ custom control), but the spec validator emits a warning.
takes the page out of its navigation and publishes it (everything that app has saved goes live with it; the page itself stays) — or detach it in Maker.
`--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.
+ When an app's navigation cannot be read, the whole check is run again, every app read afresh, three times over about 35 seconds first (another build changing
+ that app can leave it unreadable for a moment); an app still unreadable then halts the build, and one that turns out to hold the page halts it as `pages-shared-across-apps`.
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
@@ -1991,7 +1998,11 @@ custom control), but the spec validator emits a warning.
before you run the build again.
- **Not carried by teardown or download.** A teardown never deletes a configuration item (nothing proves this app
owns it); it names each one as kept, by name only, and says when a Custom API bound to a table the spec makes will
- block that table's delete. A download does not bring these items back into the spec yet.
+ block that table's delete. A plain download does not bring these items back into the spec. A managed download
+ (`--include-managed --managed-manifest <store file>`) of an app built with `configurationIdentity: "stable-v1"`
+ brings back each environment variable the store proves unchanged, without its value, default or value schema,
+ each connection reference, without its connection, and each Custom API that has no implementation yet; it never
+ brings back a duplicate rule (see `configurationIdentity` in app-spec-schema-advanced.md).
## appShell
```jsonc
diff --git a/plugins/model-apps/references/promotion.md b/plugins/model-apps/references/promotion.md
new file mode 100644
index 000000000..3968b6538
--- /dev/null
+++ b/plugins/model-apps/references/promotion.md
@@ -0,0 +1,163 @@
+# Promoting generative pages to another environment
+
+Read this only when the user asks to promote, move, ship or deploy generative pages from one
+environment to another (development to test, test to production, or to another development
+environment). It is guidance for a repeatable promotion. The skill does not export a solution for
+you; it packages the pages (Phase 6.7), writes the deployment settings file and can import a package
+you exported (`solution-settings.js`). Every platform rule below links the Microsoft Learn page that
+states it.
+
+## 1. Package the pages first
+
+Promotion moves a **solution**, so the pages must be in one. Run Phase 6.7 (`provision-solution.js`,
+then `add-page-to-solution.js`), or add the pages to the solution in Power Apps. Add every page
+explicitly by its page id: adding the app brings its site map, and a page joins the solution reliably
+only when it is added itself. Adding a page brings its file rows (`page.tsx`, `config.json`).
+
+- Generative pages are solution-aware and move between environments in a solution.
+ [Adding generative pages to solutions](https://learn.microsoft.com/power-apps/maker/model-driven-apps/generative-pages#adding-generative-pages-to-solutions)
+- Publish before you export. An unmanaged export holds only published components, so a page or a
+ navigation change saved as a draft (`--draft`) and not published does not travel.
+ [Export solutions](https://learn.microsoft.com/power-apps/maker/data-platform/export-solutions)
+
+## 2. Managed or unmanaged
+
+| Target | Export as | Why |
+| --- | --- | --- |
+| Test, UAT, production | **Managed** | Managed solutions are deployed; unmanaged ones are developed. A managed solution is a build artifact you import: it cannot be edited in the target directly. A component it brings can still be customized there when its managed properties allow it, which adds an unmanaged layer on top. |
+| Another development environment | **Unmanaged** | The receiving maker keeps editing the pages. |
+| Source control | **Unmanaged** | Unmanaged exports are the source to keep in source control. |
+
+- You cannot import a managed solution into the environment that holds the unmanaged solution it
+ came from: test a managed solution in a separate environment.
+- An unmanaged import overwrites the existing customizations of every component it holds, and you
+ cannot undo it. Deleting an unmanaged solution removes only its container, not its components.
+ [Solution concepts](https://learn.microsoft.com/power-platform/alm/solution-concepts-alm#managed-and-unmanaged-solutions),
+ [Import solutions](https://learn.microsoft.com/power-apps/maker/data-platform/import-update-export-solutions)
+
+## 3. Full solution or patch
+
+Promote the **full solution** with a higher version number by default. Use a patch only when the
+team already ships patches for this solution.
+
+| | Full solution (update or upgrade) | Patch |
+| --- | --- | --- |
+| Holds | Every component of the solution | Only what changed since the parent |
+| Can remove a component | Yes (an **upgrade** deletes components the new version no longer has) | No: a patch adds and updates only |
+| Needs in the target | Nothing (first import) or an earlier version | The parent solution, same managed or unmanaged type |
+| Version | Higher than the installed one in any position | Same major and minor as the parent, higher build or revision, and higher than every earlier patch |
+| Side effect in development | None | The parent is locked: it cannot be changed or exported while it has patches |
+
+A patch is created from an unmanaged parent with **Clone a patch**; it cannot be a patch of a patch.
+Do not import unmanaged patches into production. Learn does not recommend **Clone a patch** and
+**Clone solution** for updating a solution: they limit team development and make source control harder.
+[Create patches](https://learn.microsoft.com/power-platform/alm/create-patches-simplify-solution-updates),
+[Create and update solutions](https://learn.microsoft.com/power-platform/alm/update-solutions-alm)
+
+## 4. Version number
+
+A version is `major.minor.build.revision`. Each promotion of the same solution needs a higher
+version than the one installed in the target (for example `1.0.3.0` after `1.0.2.0`). The Power Apps
+export dialog proposes the next version and lets you type another. Record the version in
+`workflow-log.md` and in your release notes, so a later rollback can name it.
+[Update a solution: version numbers](https://learn.microsoft.com/power-apps/maker/data-platform/update-solutions#understanding-version-numbers-for-updates),
+[Export solutions](https://learn.microsoft.com/power-apps/maker/data-platform/export-solutions)
+
+## 5. Dependency check
+
+The platform fails an import when the solution needs a component that it does not hold and the
+target does not have, and warns at export about missing required components.
+[Dependency tracking](https://learn.microsoft.com/power-platform/alm/dependency-tracking-solution-components)
+A page names its tables in its code and its `config.json`, so check these yourself before you
+export. Do not rely on the export warning alone. Read only; run each check against the **target**
+environment:
+
+| A page needs | Where the page names it | Check in the target |
+| --- | --- | --- |
+| Tables | `config.json` `dataSources` | `node "${PLUGIN_ROOT}/scripts/list-tables.js" --env '<target-envUrl>' --search '<table1,table2>' --exact`: `missing` must be empty, or the tables must be in the solution (or in a solution imported first). |
+| Columns and choices | `RuntimeTypes.ts` | `node "${PLUGIN_ROOT}/scripts/genpage.js" types --env '<target-envUrl>' --data-sources '<table1,table2>' --output-file '<working-dir>/RuntimeTypes.target.ts'`, then compare it with the page's `RuntimeTypes.ts`. A column the page uses and the target lacks must travel in the solution. |
+| Connector bindings | `config.json` `connectorBindings` | Each connection reference is in the solution (Phase 6.7 `--connection-refs`), and the deployer has a connection for it in the target (step 7). |
+| Custom APIs | `config.json` `actionBindings` | `node "${PLUGIN_ROOT}/scripts/list-custom-apis.js" '<target-envUrl>' --entities '<table1,table2>'` lists them. A Custom API is deployed on its own, before the pages; it is not added by Phase 6.7. |
+| Built-in operations (`WhoAmI`, `RetrieveVersion`) | `config.json` | Nothing: the platform defines them. |
+
+Report each gap to the user with the page and the component, and stop the promotion until the gap is
+closed. Log the commands and their results in `workflow-log.md`.
+
+## 6. Import order
+
+1. Solutions the pages depend on (tables, Custom APIs, other base solutions), oldest first.
+2. The solution that holds the app and the pages.
+3. Its patches, if any, in version order. A patch needs its parent installed.
+
+An import that needs a solution that is not there yet fails with a missing dependency: install the
+dependency, then import again.
+[Import solutions](https://learn.microsoft.com/power-apps/maker/data-platform/import-update-export-solutions),
+[Create patches](https://learn.microsoft.com/power-platform/alm/create-patches-simplify-solution-updates)
+
+## 7. Connections and the import
+
+A connection reference needs a connection in the target. Supply the connection ids in a deployment
+settings file so the import does not stop to ask:
+[Connection references and environment variables in pipelines](https://learn.microsoft.com/power-platform/alm/conn-ref-env-variables-build-tools)
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/solution-settings.js" template --env '<source-envUrl>' --solution '<solutionUniqueName>' --out '<settings.json>'
+node "${PLUGIN_ROOT}/scripts/solution-settings.js" import --env '<target-envUrl>' --package '<solution.zip>' --settings '<settings.json>'
+```
+
+The deployer fills in each `ConnectionId` between the two commands. Phase 6.7's cross-environment
+note describes both commands and how the import treats a refusal. A managed import arrives
+published; an unmanaged import arrives as a draft and must be published.
+[Import solutions](https://learn.microsoft.com/power-apps/maker/data-platform/import-update-export-solutions)
+
+For an update of a managed solution, Power Apps offers three actions: **Upgrade** (the default:
+deletes components the new version no longer holds), **Stage for upgrade** (installs the new version
+beside the old one until you apply the upgrade) and **Update** (replaces the solution and deletes
+nothing).
+[Update a solution](https://learn.microsoft.com/power-apps/maker/data-platform/update-solutions)
+
+## 8. Rollback
+
+Plan the rollback before the import:
+
+- **Keep the previous release.** Keep each exported package and its version, and keep the pages in
+ source control (see "Pulling existing pages into the project" in the skill). The target holds only
+ the version you imported.
+- **Roll forward.** To go back, rebuild the earlier release in development (put the earlier
+ `page.tsx` back and upload it), export it with a **higher** version number, and import it as an
+ update. This restores the code without removing what the solution installed; it does not bring back
+ data an earlier upgrade or migration deleted (an upgrade deletes the components the new version no
+ longer holds, with their data).
+- **Stage for upgrade** keeps the old version installed until you apply the upgrade, so you can check
+ the new version first.
+ [Update a solution](https://learn.microsoft.com/power-apps/maker/data-platform/update-solutions)
+- **Deleting a managed solution** removes everything it installed, including the data in the custom
+ tables and custom columns it brought. Do not delete one as a rollback unless the user accepts that
+ data loss.
+ [Solution concepts](https://learn.microsoft.com/power-platform/alm/solution-concepts-alm#managed-and-unmanaged-solutions)
+- **Back up the target before an import that cannot be undone:** any unmanaged import, and any
+ upgrade that removes components (and so their data). Restoring a backup is the only way to get
+ deleted data back.
+ [Import solutions](https://learn.microsoft.com/power-apps/maker/data-platform/import-update-export-solutions)
+
+## 9. What travels with a page, and what does not
+
+| Travels with the page | Does not travel |
+| --- | --- |
+| The published page code (`page.tsx`) and `config.json`: model, data sources, connector bindings, Custom API bindings | The full authoring conversation: in the target, the designer shows only the first prompt and the published code |
+| The page's id, so a later import updates the same page | Earlier versions of the page: the page holds its current code only. Keep earlier versions in source control |
+| The app's navigation entry, when the app and its site map are in the solution | A draft that was saved and not published |
+| | The tables, columns and Custom APIs the page uses, unless they are in the solution (step 5) |
+| | Connections: the target supplies its own through the connection references (step 7) |
+| | The data in the tables |
+
+The conversation rule is stated in
+[Adding generative pages to solutions](https://learn.microsoft.com/power-apps/maker/model-driven-apps/generative-pages#adding-generative-pages-to-solutions).
+For a review, compare the page code in source control, not the authoring conversation.
+
+## 10. Record the promotion
+
+Append a `## Promotion` section to `workflow-log.md`: the source and target environments as
+`<source-envUrl>` and `<target-envUrl>` placeholders when the log is shared, the solution, the
+version, managed or unmanaged, full or patch, every dependency check command and its result, the
+import result, and the rollback plan.
diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.js
index c720571a4..2bd2e9a35 100644
--- a/plugins/model-apps/scripts/build-model-app.js
+++ b/plugins/model-apps/scripts/build-model-app.js
@@ -79,8 +79,7 @@ const { createPassthroughCreates } = require('./lib/creates-passthrough.js');
// against, read as list-connections.js reads it (the SDK first, pac when the SDK's route is refused).
const { configurationAuthorizationKeys, readDeploymentBindings, usesConfiguration } = require('./lib/configuration-artifacts.js');
const { configurationSendOnce } = require('./lib/configuration-transport.js');
-const { sdkFirst, connectivity } = require('./lib/sdk-first.js');
-const { connectionRowFromSdk, listConnectionsWithPac } = require('./list-connections.js');
+const { readConnections } = require('./list-connections.js');
const { isDeclaredView, compileViewIntent } = require('./lib/view-reconcile.js');
const { approvalKey } = require('./lib/reconcile-common.js');
const { isDeclaredChart, compileChartIntent } = require('./lib/chart-reconcile.js');
@@ -937,13 +936,7 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {
// The connections a declared connection reference may be bound to, read as list-connections.js reads them. A function, called by the
// configuration step only when a binding or a page's readiness needs proof (once per pass), so a spec without references never reads them.
// Without an environment (a test double) there is no reader, and a bound reference stays unproven rather than assumed bound.
- const connections = deps.connections || (opts.env
- ? async () => (await sdkFirst(opts.env, {
- ...connectivity,
- fromSdk: async (sdk) => (await sdk.listConnections()).map(connectionRowFromSdk),
- fromPac: async (refusal) => listConnectionsWithPac(opts.env, refusal),
- })).value
- : undefined);
+ const connections = deps.connections || (opts.env ? async () => (await readConnections(opts.env)).value : undefined);
// 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
diff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.js
index efe014f8c..9dd2eb839 100644
--- a/plugins/model-apps/scripts/download-model-app.js
+++ b/plugins/model-apps/scripts/download-model-app.js
@@ -30,6 +30,13 @@
// this publisher's own unmanaged script (lib/declared-form-io.js libraryEntry; `managedForms.libraries`).
// A persona a declared flow's securityRoles name that the downloaded spec lacks is read from its role and written into personas[] only
// when a rebuild provably leaves that role exactly as it is (lib/persona-restore.js; `managedBpfs.personas`).
+// A declared view (views[].reconcile "declared") a stable build (createIdentity "stable-v1") created, settled and still proves is
+// written into views[] as a declaration inverted from the row, pinned to its id, only when it compiles back to the row exactly and
+// the build's planner answers noChange for it (lib/declared-view-io.js; `managedViews`), and is then no longer named as left out;
+// any other is named in `managedViews.omitted` and stays in the not-round-tripped report.
+// A declared chart a stable build created is restored the same way into charts[], without an id (a chart declaration has none: the
+// store's key selects the row), only when verify's content checks pass on its published row and the planner answers noChange
+// (lib/declared-chart-io.js; `managedCharts`); any other is named in `managedCharts.omitted`.
// A declared form or flow that is proved but left out only for what the download cannot bring (the script library a form handler
// calls, the persona a flow's securityRoles name) is written ready to paste, with what it still needs, to
// a NEW file `<out>/.maker-workspace/managed-fragments-<UTC time>-<random>.json` (`managedFragments.file` in the result;
@@ -61,7 +68,7 @@
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
-const { assertSafeOutputDir, assertPlainFileTarget, writeFileSafe, removeTreeWithRetry } = require('./lib/safe-fs.js');
+const { assertSafeOutputDir, assertPlainFileTarget, assertFileReplaceable, writeFileSafe, removeTreeWithRetry } = require('./lib/safe-fs.js');
const { renameWithRetry } = require('./lib/rename-retry.js');
const { parseArgs, validateFlags, emitResult, preflightAuth, dataverseOrigin, requireDataverseOrigin, webApiUrl, readOrgLanguageCode, readLanguageCodeFlag } = require('./lib/dataverse-auth.js');
const { writeBaseline } = require('./lib/deployed-baseline.js');
@@ -74,6 +81,11 @@ const { restoreManagedForms } = require('./lib/declared-form-io.js');
const { restoreManagedDashboards } = require('./lib/declared-dashboard-io.js');
const { restoreManagedRules } = require('./lib/declared-rule-io.js');
const { restoreManagedBpfs } = require('./lib/declared-bpf-io.js');
+const { restoreManagedViews } = require('./lib/declared-view-io.js');
+const { restoreManagedCharts } = require('./lib/declared-chart-io.js');
+const { restoreManagedConfiguration } = require('./lib/declared-configuration-io.js');
+const { readConnections } = require('./list-connections.js');
+const { subtractRestored, storeRevision, assertStoreUnchanged, omission } = require('./lib/managed-restore-report.js');
const { settleFragments } = require('./lib/managed-fragments.js');
const { fetchSitemap, sitemapGenPages, appNavigationMatchesSitemap } = require('./lib/sitemap-pages.js');
const { isRestrictedSolution } = require('./lib/system-solutions.js');
@@ -84,7 +96,7 @@ const { labelsByLcid, pickLabel, 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, setAppThemeFloor } = require('./lib/app-components.js');
const { mapLimit, DEFAULT_MAX_SIZE_KB } = require('./lib/entity-provision.js');
-const { downloadedChoiceOptions, downloadedColumnFeatures, downloadedTableFlags, readTableFlags, setSchemaFeaturesFloor } = require('./lib/schema-feature-contract.js');
+const { downloadedChoiceOptions, downloadedColumnFeatures, downloadedTableFlags, readTableFlags, setSchemaFeaturesFloor, SYSTEM_ADMIN_PROFILE_ID, SYSTEM_ADMIN_PROFILE_NAME } = require('./lib/schema-feature-contract.js');
const { readExistingDateBehaviors } = require('./lib/date-behavior.js');
const { compareText } = require('./lib/compare-text.js');
const { hostsCustomControl } = require('./lib/dashboard-tiles.js');
@@ -884,7 +896,7 @@ async function readAppShellSettings(sdk, appId) {
return out;
}
-async function readDescriptionInventory(sdk, appId, solutionScope, referencedGlobalChoices, componentInventory, { tables } = {}) {
+async function readDescriptionInventory(sdk, appId, solutionScope, referencedGlobalChoices, componentInventory, { tables, securedColumns } = {}) {
// `incomplete[]` records an artifact class whose read FAILED. Without it the whole app-component
// block shared one broad catch, so a 403 on `systemform` left `forms: []` — indistinguishable from
// an app with no forms, which is EXACTLY the reported bug (AB#6686423) reappearing inside the fix
@@ -892,7 +904,9 @@ async function readDescriptionInventory(sdk, appId, solutionScope, referencedGlo
// keys reach `app-spec.json`, so this informs the CLI without changing the spec shape.
//
// `tables` are the app's tables, whose command bars are inventoried (readCommandInventory); a caller that names none reads none.
- const inventory = { views: [], charts: [], forms: [], businessRules: [], globalChoices: [], commands: [], roleRestrictedForms: [], incomplete: [] };
+ // `securedColumns` are the { table, column } logical names the download emits with isSecured, whose field security profiles are
+ // named (readFieldSecurityProfiles); a caller that names none looks for profiles in the app's solution only.
+ const inventory = { views: [], charts: [], forms: [], businessRules: [], globalChoices: [], commands: [], roleRestrictedForms: [], fieldSecurityProfiles: [], incomplete: [] };
const fail = (kind, err) => inventory.incomplete.push({ kind, reason: (err && err.message) ? String(err.message).slice(0, 200) : 'read failed' });
try {
const layer = componentInventory ? componentInventory.layer : await currentAppLayer(sdk.dataverse, appId);
@@ -1079,15 +1093,99 @@ async function readDescriptionInventory(sdk, appId, solutionScope, referencedGlo
}
}
+ await readFieldSecurityProfiles(sdk, inventory, { solIds, solutionError, securedColumns });
+
// Ordered here, once, for everything that reads the inventory — the spec's `descriptionInventory`, the not-round-tripped report
// and the role-restriction warning. The rows are in the order Dataverse answered, which differs between two reads of one app; by
// table, then name, then id (compareArtifacts) they do not.
for (const key of ['views', 'charts', 'forms', 'businessRules', 'commands', 'roleRestrictedForms']) inventory[key].sort(compareArtifacts);
inventory.globalChoices.sort((a, b) => compareText(a.name, b.name));
+ inventory.fieldSecurityProfiles.sort((a, b) => compareText(a.name, b.name) || compareText(a.id, b.id));
inventory.incomplete.sort((a, b) => compareText(a.kind, b.kind) || compareText(a.reason, b.reason));
return Object.fromEntries(Object.entries(inventory).filter(([, value]) => value.length));
}
+// Field security profiles: REPORTED, never declared. A profile is environment-wide security policy — its permissions say which
+// secured columns its holders may read or change, and its users and teams say who holds it — and no binding store record proves
+// that this app authored one, so a download that declared it would hand a rebuild the power to rewrite somebody else's grant.
+// The download names the custom profiles it finds instead, in BOTH a plain and a managed download, and leaves fieldSecurityProfiles[]
+// out of the spec: a rebuild then neither changes nor recreates them. The secured columns themselves still round-trip (isSecured).
+//
+// Two ways in, de-duplicated by id:
+// - the app's own solution(s): solution component type 70 is a Field Security Profile
+// (https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/solutioncomponent);
+// - a field permission on a column the download emits as secured — the profile that opens it, wherever it lives
+// (https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/fieldpermission).
+// Only the profile id (`_fieldsecurityprofileid_value`) of a permission is read, and only the id and name of a profile: never a
+// permission's can-read/create/update bits, and never the users or teams a profile is given to, so nothing about who may see what
+// leaves the environment. System Administrator is dropped by its fixed id AND by its name — every org has it, every secured column
+// opens to it, and naming it would only bury the custom profiles the note is for.
+//
+// A failed read is UNKNOWN, never "no profiles": one `incomplete` entry with a FIXED reason (the service's error text can quote the
+// filter, i.e. the column names) — and what the other way in found is kept.
+const FIELD_SECURITY_PROFILES_UNREAD = 'the field security profiles could not be read';
+async function readFieldSecurityProfiles(sdk, inventory, { solIds = [], solutionError = null, securedColumns = [] } = {}) {
+ let failed = false;
+ const ids = [];
+ try {
+ if (solutionError) throw solutionError;
+ for (const solId of solIds) {
+ const comps = await sdk.queryRecords('solutioncomponent', { select: ['objectid'], filter: `_solutionid_value eq ${solId} and componenttype eq 70`, paginate: true });
+ ids.push(...(comps || []).map((r) => r && r.objectid).filter(Boolean));
+ }
+ } catch {
+ failed = true;
+ }
+ // One request per table, naming its secured columns, so the read is bounded by what the download emits.
+ const byTable = new Map();
+ for (const { table, column } of securedColumns || []) {
+ if (!table || !column) continue;
+ const t = String(table).toLowerCase();
+ if (!byTable.has(t)) byTable.set(t, new Set());
+ byTable.get(t).add(String(column).toLowerCase());
+ }
+ const esc = (v) => v.replace(/'/g, "''");
+ for (const table of [...byTable.keys()].sort(compareText)) {
+ try {
+ const columns = [...byTable.get(table)].sort(compareText).map((c) => `attributelogicalname eq '${esc(c)}'`).join(' or ');
+ const rows = await sdk.queryRecords('fieldpermission', { select: ['_fieldsecurityprofileid_value'], filter: `entityname eq '${esc(table)}' and (${columns})`, paginate: true });
+ ids.push(...(rows || []).map((r) => r && r._fieldsecurityprofileid_value).filter(Boolean));
+ } catch {
+ failed = true;
+ }
+ }
+ const isAdmin = (id) => String(id || '').replace(/[{}]/g, '').toLowerCase() === SYSTEM_ADMIN_PROFILE_ID;
+ const custom = ids.filter((id) => !isAdmin(id));
+ if (custom.length) {
+ try {
+ const rows = await rowsByIds(sdk, 'fieldsecurityprofile', 'fieldsecurityprofileid', custom, ['fieldsecurityprofileid', 'name'], (r) => r);
+ const seen = new Set();
+ for (const r of rows) {
+ const id = String((r && r.fieldsecurityprofileid) || '').replace(/[{}]/g, '').toLowerCase();
+ if (!id || seen.has(id) || isAdmin(id)) continue;
+ if (String((r && r.name) || '').trim().toLowerCase() === SYSTEM_ADMIN_PROFILE_NAME.toLowerCase()) continue;
+ seen.add(id);
+ inventory.fieldSecurityProfiles.push({ id, name: r.name });
+ }
+ } catch {
+ failed = true;
+ }
+ }
+ if (failed) inventory.incomplete.push({ kind: 'fieldSecurityProfiles', reason: FIELD_SECURITY_PROFILES_UNREAD });
+}
+
+// The inventory's field security profiles as managed-restore-report omissions (id and name, fixed reason), for the NOTE and the
+// result payload. Ownership-unproven is the honest code: the profile may well be this app's, but nothing binding says so.
+function fieldSecurityProfileOmissions(inventory) {
+ return ((inventory && inventory.fieldSecurityProfiles) || []).map((p) => omission({ kind: 'fieldSecurityProfile', id: p.id, name: p.name, code: 'ownership-unproven' }));
+}
+
+function fieldSecurityProfilesNote(omitted) {
+ if (!omitted || !omitted.length) return '';
+ const n = omitted.length;
+ return `NOTE: ${n} field security profile${n === 1 ? '' : 's'} (${omitted.map((o) => o.name || o.id).join(', ')}) ${n === 1 ? 'is' : 'are'} not declared in fieldSecurityProfiles[]: ${omitted[0].reason}. ${n === 1 ? 'It stays' : 'They stay'} as ${n === 1 ? 'it is' : 'they are'} in this environment, and a rebuild neither changes nor recreates ${n === 1 ? 'it' : 'them'}; the secured columns keep isSecured. Declare a profile only if this app owns it.\n`;
+}
+
// Read the page tree a download writes (<pagesRoot>/<pageId>/{page.tsx,config.json,prompt.txt}) into
// pages[] entries with codeFile paths relative to `outDir`. The same layout is what scripts/genpage.js download writes (both through
// lib/genpage-sdk.js `pageFolderFiles`) and what an earlier release's `pac model genpage download` wrote, so a folder downloaded by either is read the same way.
@@ -1941,6 +2039,21 @@ function roundTrippedAware(inventory, globalChoiceDecls) {
return remaining.length ? { ...rest, globalChoices: remaining } : rest;
}
+// The not-round-tripped report of a download: its inventory less the global choices the spec declares (roundTrippedAware), with the
+// app-membership notes. One function for the two places that compute it — downloadApp, and main once the managed download has put
+// some of the inventory back into the spec (lib/managed-restore-report.js subtractRestored) — so the two can never disagree.
+//
+// Round-tripped means DECLARED in the emitted spec, so subtract `spec.globalChoices` — not the raw
+// `globalChoiceDecls` candidates, which also hold sets bound only by a filtered attribute or a
+// dropped table. Subtracting those hid a set the spec never re-declares: a silent loss in the one
+// report whose job is naming them.
+function notRoundTrippedReport(inventory, spec, membershipNotes) {
+ const declaredGlobalChoices = new Set((spec.globalChoices || []).map((g) => String(g && g.name).toLowerCase()));
+ const summary = notRoundTrippedSummary(roundTrippedAware(inventory, declaredGlobalChoices));
+ if (!membershipNotes.length) return summary;
+ return { ...(summary || { classes: [], total: 0, entities: [] }), appMembership: membershipNotes };
+}
+
// Render `notRoundTrippedSummary` as the operator-facing warning. Kept separate from the computation
// so the wording is testable without a download, and so the same summary can be emitted as JSON.
function notRoundTrippedWarning(summary) {
@@ -3385,7 +3498,7 @@ async function runDownload(options = {}) {
return { ...result, stagedPages: { check: () => assertPageTreeReplaceable(pagesRoot), publish: () => writePageTree(pagesRoot, pages) } };
}
-async function downloadApp({ sdk, genpage, outDir, appId, appUnique, allowLossy = false, resetPageKeys = false, concurrency, languageCode, includeCapabilities = false, captureTheme = includeCapabilities, stage = null }) {
+async function downloadApp({ sdk, genpage, outDir, appId, appUnique, allowLossy = false, resetPageKeys = false, concurrency, languageCode, includeCapabilities = false, captureTheme = includeCapabilities, stage = null, deferReport = false }) {
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.
@@ -4025,7 +4138,10 @@ async function downloadApp({ sdk, genpage, outDir, appId, appUnique, allowLossy
const scope = solutionUnreadable
? new Error(`the solutions this app belongs to could not be read (${solutionUnreadable})`)
: (solutionCandidates || solution.uniqueName);
- capturedInventory = await readDescriptionInventory(sdk, appId, scope, referenced, componentInventory, { tables: [...allLogicals, ...appTables] });
+ // The columns this download secures, whose field security profiles the inventory names (readFieldSecurityProfiles).
+ const securedColumns = [];
+ for (const e of entities || []) for (const c of (e && e.columns) || []) if (c && c.isSecured === true && e.schemaName && c.schemaName) securedColumns.push({ table: String(e.schemaName).toLowerCase(), column: String(c.schemaName).toLowerCase() });
+ capturedInventory = await readDescriptionInventory(sdk, appId, scope, referenced, componentInventory, { tables: [...allLogicals, ...appTables], securedColumns });
return capturedInventory;
},
};
@@ -4063,25 +4179,32 @@ async function downloadApp({ sdk, genpage, outDir, appId, appUnique, allowLossy
// reported failure was not that they are omitted — that is a documented limitation — but that
// NOTHING said so, so a second session reading the spec could not tell "this app has no views"
// from "this download does not carry views".
- //
- // Round-tripped means DECLARED in the emitted spec, so subtract `spec.globalChoices` — not the raw
- // `globalChoiceDecls` candidates, which also hold sets bound only by a filtered attribute or a
- // dropped table. Subtracting those hid a set the spec never re-declares: a silent loss in the one
- // report whose job is naming them.
- const declaredGlobalChoices = new Set((spec.globalChoices || []).map((g) => String(g && g.name).toLowerCase()));
- let notRoundTripped = notRoundTrippedSummary(roundTrippedAware(capturedInventory, declaredGlobalChoices));
// The notes come in the order the component rows were read, which Dataverse does not fix (compareNotes).
const membershipNotes = [...componentInventory.notes, ...mainFormMembership.notes].sort(compareNotes);
- if (membershipNotes.length) {
- notRoundTripped = { ...(notRoundTripped || { classes: [], total: 0, entities: [] }), appMembership: membershipNotes };
- }
- if (notRoundTripped) process.stderr.write(notRoundTrippedWarning(notRoundTripped));
+ const notRoundTripped = notRoundTrippedReport(capturedInventory, spec, membershipNotes);
+ // `deferReport` (main's managed download, and only it): the report is not printed here but handed back as its parts
+ // (`deferredReport`), because the managed restore may yet put some of what it names back into the spec. main prints it once,
+ // after the restore, without what was restored. Every other caller gets the report printed here, as it always was.
+ if (notRoundTripped && !deferReport) process.stderr.write(notRoundTrippedWarning(notRoundTripped));
if (relationshipsSkipped.length) process.stderr.write(relationshipsSkippedWarning(relationshipsSkipped));
+ // Printed by every download, plain and managed alike: no restore declares a profile (readFieldSecurityProfiles).
+ const fieldSecurityOmitted = fieldSecurityProfileOmissions(capturedInventory);
+ if (fieldSecurityOmitted.length) process.stderr.write(fieldSecurityProfilesNote(fieldSecurityOmitted));
const droppedSubareas = typeof spec.droppedSubareas === 'number' ? spec.droppedSubareas : droppedSubareaCount(app, spec);
const droppedSubareaDetails = Array.isArray(spec.droppedSubareaDetails) ? spec.droppedSubareaDetails : [];
// `publisher` is internal (main hands it to the managed restore, which downloads a form's handler library only under this
// publisher's verified prefix); it is not part of the printed result.
- return { ok: true, spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped, relationships, relationshipsSkipped, publisher: { prefix: solution.publisherPrefix, resolved: solution.prefixResolved }, ...(navIdsLeft.length ? { navIdsLeft } : {}), ...(pageBindings ? { pageBindings } : {}), ...(solutionCandidates ? { solutionCandidates } : {}) };
+ return { ok: true, spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped, relationships, relationshipsSkipped, publisher: { prefix: solution.publisherPrefix, resolved: solution.prefixResolved }, ...(navIdsLeft.length ? { navIdsLeft } : {}), ...(pageBindings ? { pageBindings } : {}), ...(solutionCandidates ? { solutionCandidates } : {}), ...(fieldSecurityOmitted.length ? { fieldSecurityProfiles: { omitted: fieldSecurityOmitted } } : {}), ...(deferReport ? { deferredReport: { inventory: capturedInventory, membershipNotes } } : {}) };
+}
+
+// `error` with `sequel` (what the refusal or failure means for the app folder) added to its message. Its code and reason are kept, so a
+// caller that tells one failure from another by them still can; the original is its cause.
+function withSequel(error, sequel) {
+ if (!error || typeof error.message !== 'string') return error;
+ const told = new Error(`${error.message.replace(/\.\s*$/, '')}. ${sequel}`, { cause: error });
+ if (error.code !== undefined) told.code = error.code;
+ if (error.reason !== undefined) told.reason = error.reason;
+ return told;
}
async function main(deps = {}) {
@@ -4214,12 +4337,13 @@ async function main(deps = {}) {
// Every download stages its page tree (runDownload `stagePages`): it is checked and published below, after everything that can still
// stop the download, so a refusal or a failure before then leaves the maker's pages/ exactly as it was.
- const result = await io.runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy: allowLossyDownload, resetPageKeys, languageCode: session.languageCode, includeCapabilities, stagePages: true });
+ const result = await io.runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy: allowLossyDownload, resetPageKeys, languageCode: session.languageCode, includeCapabilities, stagePages: true, ...(includeManaged ? { deferReport: true } : {}) });
// The run's last writes: these lines, then the result and the exit, with no turn of the event loop between them — made blocking (lib/output-redaction.js).
makeWritesBlocking(process.stdout, io.stderr);
if (!result.ok) { finish(false, result); return; }
- const { spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped, solutionCandidates, navIdsLeft, pageBindings } = result;
+ const { spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, solutionCandidates, navIdsLeft, pageBindings, fieldSecurityProfiles } = result;
+ let { notRoundTripped } = result;
if (droppedSubareas > 0 || dashboardReconstructionError) {
const droppedList = (droppedSubareaDetails || [])
.map((d) => `${d.type}${d.id ? `:${d.id}` : ''}${d.title ? ` (${d.title})` : ''}`)
@@ -4249,15 +4373,27 @@ async function main(deps = {}) {
// dashboards[], in place of the plain entry the download reconstructed for it (lib/declared-dashboard-io.js restoreManagedDashboards),
// and each declared business rule into businessRules[] (lib/declared-rule-io.js restoreManagedRules), which the plain download leaves out;
// and each declared business process flow into businessProcessFlows[] (lib/declared-bpf-io.js restoreManagedBpfs), which it leaves out too;
+ // and each declared view a stable build created into views[] (lib/declared-view-io.js restoreManagedViews), which it leaves out too;
+ // and each declared chart a stable build created into charts[] (lib/declared-chart-io.js restoreManagedCharts), which it leaves out too;
// every other is named, never silently dropped. A store file that is not this app's on this environment stops the download before
// anything is written.
let managedForms = null;
let managedDashboards = null;
let managedRules = null;
let managedBpfs = null;
+ let managedViews = null;
+ let managedCharts = null;
+ let managedConfiguration = null;
// The proved items the restore leaves out only for what the download cannot bring (lib/managed-fragments.js).
const fragments = [];
+ // The store's bytes as the restore first reads them: every family below reads the file on its own, so a build that rewrote it
+ // in between would have them prove against two revisions. Rechecked before anything is published (assertStoreUnchanged). A
+ // store that cannot be read here is left to the restore, which names a missing or foreign file in its own words.
+ let storeRev = null;
+ // The ids the restore put back into the spec, by inventory class (lib/managed-restore-report.js subtractRestored).
+ const restoredIds = {};
if (includeManaged) {
+ try { storeRev = storeRevision(managedManifestFile); } catch { /* named by the restore below */ }
const source = {
sdk,
spec,
@@ -4268,12 +4404,20 @@ async function main(deps = {}) {
validate: (s) => io.validateAppSpec(s, { profile: 'plan', reconstructed: true }),
fragments,
publisher: result.publisher,
+ // The environment's connections, read as a build reads them (list-connections.js readConnections), and only when a page names a
+ // connection reference whose row holds a connection: such a reference is restored only when they prove it bound to its connector,
+ // the proof the rebuild's page gate asks for (lib/declared-configuration-io.js acceptReference). A failed read proves nothing, so
+ // the reference is left out (page-unready); it never stops the download.
+ connections: deps.connections || (async () => (await readConnections(dataverseOrigin(env))).value),
};
try {
managedForms = await restoreManagedForms(source);
managedDashboards = await restoreManagedDashboards(source);
managedRules = await restoreManagedRules(source);
managedBpfs = await restoreManagedBpfs(source);
+ managedViews = await restoreManagedViews(source);
+ managedCharts = await restoreManagedCharts(source);
+ managedConfiguration = await restoreManagedConfiguration(source);
} catch (e) {
finish(false, { ok: false, code: (e && e.code) || 'managed-manifest-unusable', error: `${(e && e.message) || e}. Nothing was written.` });
return;
@@ -4284,6 +4428,22 @@ async function main(deps = {}) {
for (const s of managedRules.stale) io.stderr.write(`WARNING: managed business rule ${s.key} was not restored: ${s.reason}. It is left out of businessRules[], as every business rule is without --include-managed.\n`);
for (const s of managedBpfs.stale) io.stderr.write(`WARNING: managed business process flow ${s.key} was not restored: ${s.reason}. It is left out of businessProcessFlows[], as every process flow is without --include-managed.\n`);
for (const p of managedBpfs.personas || []) io.stderr.write(`NOTE: persona '${p.name}' was written from its role as it is now; a build owns a persona's role, so a privilege added to that role outside the spec is removed by the next build.\n`);
+ for (const o of managedViews.omitted) io.stderr.write(`WARNING: managed view ${o.key || o.id} was not restored: ${o.reason}. It is left out of views[], as every view is without --include-managed.\n`);
+ restoredIds.views = managedViews.restored.map((r) => r.id);
+ for (const o of managedCharts.omitted) io.stderr.write(`WARNING: managed chart ${o.key || o.id} was not restored: ${o.reason}. It is left out of charts[], as every chart is without --include-managed.\n`);
+ restoredIds.charts = managedCharts.restored.map((r) => r.id);
+ // Protected configuration (lib/declared-configuration-io.js): an item left out is named as every family's is; an item restored
+ // without some of its parts (a default, a value, a connection) names those parts, never their values.
+ for (const [list, r] of Object.entries(managedConfiguration)) {
+ for (const o of r.omitted) io.stderr.write(`WARNING: managed ${o.kind} ${o.key || o.id} was not restored: ${o.reason}. It is left out of ${list}[], as every ${o.kind} is without --include-managed.\n`);
+ for (const w of r.withheld) io.stderr.write(`NOTE: managed ${w.kind} ${w.key || w.id} was restored without ${w.fields.join(', ')}: ${w.reason}.\n`);
+ }
+ // The report runDownload deferred (`deferReport`), less what was restored, printed once. A runDownload that hands back no
+ // deferred parts printed its own report already (or had none), so nothing is printed twice.
+ if (result.deferredReport) {
+ notRoundTripped = notRoundTrippedReport(subtractRestored(result.deferredReport.inventory, restoredIds), spec, result.deferredReport.membershipNotes);
+ if (notRoundTripped) io.stderr.write(notRoundTrippedWarning(notRoundTripped));
+ }
}
const validation = io.validateAppSpec(spec, { profile: 'plan', reconstructed: true });
if (!validation.ok) {
@@ -4303,11 +4463,30 @@ async function main(deps = {}) {
);
}
// The staged page tree is published here, for every download, after validation and everything else that can stop the download: its
- // checks first (writePageTree's own refusals, made without writing), then, for the managed download, the fragments file, then the
- // tree, and only then the spec and the baseline. So a refusal or a failed write before this point leaves pages/, the spec and the
- // baseline as they were, and a tree that cannot be replaced stops the managed download before its fragments file is written.
+ // checks first (writePageTree's own refusals, made without writing, and the refusals writeFileSafe would make of app-spec.json —
+ // a link, a folder, a hard link, a read-only file or a folder where no new file can be made), then, for the managed download, the
+ // fragments file, then the tree, and only then the spec and the baseline. So a refusal or a failed write before this point leaves
+ // pages/, the spec and the baseline as they were, and a tree or a spec that cannot be replaced stops the managed download before its
+ // fragments file is written, with or without a page tree: a managed download of an app with no generative pages has no tree to check,
+ // but its fragments file is still written before the spec. The spec is still written after the tree, and the two are not one transaction: a write of it that
+ // fails for a reason no look beforehand can see (a full disk, a lock taken meanwhile) comes after the tree is published.
let managedFragments = null;
- if (result.stagedPages) result.stagedPages.check();
+ if (includeManaged) {
+ try {
+ assertStoreUnchanged(managedManifestFile, storeRev);
+ } catch (e) {
+ finish(false, { ok: false, code: e.code, error: `${e.message}. Nothing was written.` });
+ return;
+ }
+ }
+ if (result.stagedPages || includeManaged) {
+ if (result.stagedPages) result.stagedPages.check();
+ try {
+ assertFileReplaceable(specPath);
+ } catch (e) {
+ throw withSequel(e, `The download stopped before replacing anything: ${path.join(outDir, 'pages')} and ${specPath} are as they were`);
+ }
+ }
if (includeManaged) {
try {
managedFragments = settleFragments(outDir, { app: appUnique, items: fragments });
@@ -4320,7 +4499,16 @@ async function main(deps = {}) {
}
}
if (result.stagedPages) result.stagedPages.publish();
- writeFileSafe(specPath, JSON.stringify(spec, null, 2));
+ try {
+ writeFileSafe(specPath, JSON.stringify(spec, null, 2));
+ } catch (e) {
+ if (!result.stagedPages) throw e;
+ // Only what is known is said: the page tree was published, and then the write of the spec reported an error. What the spec on
+ // disk is now, and whether it matches the pages, is not: the app may be unchanged (the spec already matched), a rename can take
+ // effect and still report an error, and the swap keeps the previous tree when it cannot remove its folder (writePageTree warns
+ // of that itself). Running the same download again writes both once the cause is resolved.
+ throw withSequel(e, `This download had already published its page tree to ${path.join(outDir, 'pages')} when the write of ${specPath} reported this error, so whether ${specPath} matches those pages has not been confirmed: resolve the error and run the same download again`);
+ }
// AB#6726727: the spec just written is this app's server-current edit snapshot, so it is the baseline a later build
// lines the live sitemap up against — a nav change made in the designer after this download is then
// kept, not reverted by the now-stale spec. Its dashboard and page ids were read from this
@@ -4335,9 +4523,22 @@ async function main(deps = {}) {
} catch (e) {
if (e && e.code === 'UNSAFE_OUTPUT') io.stderr.write(`WARNING: ${e.message}\n`);
}
+ // A view or chart restore says something only when it restored or left out a group: a store with neither family answers the
+ // result a managed download gave before views and charts were restored, byte for byte.
+ const familyResult = (r) => (r && (r.restored.length || r.omitted.length) ? { restored: r.restored.map((x) => x.key), omitted: r.omitted } : null);
+ const viewsResult = familyResult(managedViews);
+ const chartsResult = familyResult(managedCharts);
+ // A configuration list says something only when it restored, left out or withheld part of an item, under its own key, so a store
+ // without protected configuration answers the result a managed download gave before it was restored, byte for byte.
+ const CONFIGURATION_RESULTS = { environmentVariables: 'managedEnvironmentVariables', connectionReferences: 'managedConnectionReferences', customApis: 'managedCustomApis', duplicateDetectionRules: 'managedDuplicateDetectionRules' };
+ const configurationResults = {};
+ for (const [list, r] of Object.entries(managedConfiguration || {})) {
+ if (!r.restored.length && !r.omitted.length && !r.withheld.length) continue;
+ configurationResults[CONFIGURATION_RESULTS[list]] = { restored: r.restored.map((x) => x.key), omitted: r.omitted, ...(r.withheld.length ? { withheld: r.withheld } : {}) };
+ }
// Each optional field is in the result only when it has something to say. `navIdsLeft` is absent in the usual case (runDownload leaves it out when no id is
// left) and could be an empty list from another producer, so it is checked for both: an empty list is no finding.
- finish(true, { ok: true, spec: specPath, pages: pages.length, entities: entities.length, webResources: webResources.length, droppedSubareas, ...(notRoundTripped ? { notRoundTripped } : {}), ...(defaulted.length ? { directEntryDefaulted: defaulted } : {}), ...(navIdsLeft && navIdsLeft.length ? { navIdsLeft } : {}), ... (pageBindings ? { pageBindings } : {}), ...(solutionCandidates ? { solutionCandidates } : {}), ...(managedForms ? { managedForms } : {}), ...(managedDashboards ? { managedDashboards } : {}), ...(managedRules ? { managedRules } : {}), ...(managedBpfs ? { managedBpfs } : {}), ...(managedFragments ? { managedFragments } : {}) });
+ finish(true, { ok: true, spec: specPath, pages: pages.length, entities: entities.length, webResources: webResources.length, droppedSubareas, ...(notRoundTripped ? { notRoundTripped } : {}), ...(defaulted.length ? { directEntryDefaulted: defaulted } : {}), ...(navIdsLeft && navIdsLeft.length ? { navIdsLeft } : {}), ... (pageBindings ? { pageBindings } : {}), ...(solutionCandidates ? { solutionCandidates } : {}), ...(managedForms ? { managedForms } : {}), ...(managedDashboards ? { managedDashboards } : {}), ...(managedRules ? { managedRules } : {}), ...(managedBpfs ? { managedBpfs } : {}), ...(viewsResult ? { managedViews: viewsResult } : {}), ...(chartsResult ? { managedCharts: chartsResult } : {}), ...configurationResults, ...(managedFragments ? { managedFragments } : {}), ...(fieldSecurityProfiles ? { fieldSecurityProfiles } : {}) });
} finally {
try { if (session) session.cleanup(); } catch { /* best-effort: the result below matters more */ }
if (outcome) io.emitResult(...outcome);
@@ -4408,4 +4609,4 @@ if (require.main === module) {
main().catch((err) => emitResult(false, err));
}
-module.exports = { untypedColumnNames, untypedColumnWarnings, collectGlobalChoices, finalizeGlobalChoices, roundTrippedAware, isRoleRestrictedFormXml, notRoundTrippedSummary, notRoundTrippedWarning, relationshipsSkippedWarning, labelFromDataverse, columnDisplayName, resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, pageBindingsReport, pageBindingsNote, readPreviousPageKeys, assignPageKeys, missingDownloads, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, readAppShellSettings, iconWebResources, readDashboards, readRelationships, droppedSubareaCount, recoverAppSolution, runDownload, writePageTree, generatedFolders, GUARDED_FS_METHODS, preserveAuthoredLanguageCode, makeDownloadSdk, compareText, main };
+module.exports = { untypedColumnNames, untypedColumnWarnings, collectGlobalChoices, finalizeGlobalChoices, roundTrippedAware, isRoleRestrictedFormXml, notRoundTrippedSummary, notRoundTrippedReport, notRoundTrippedWarning, relationshipsSkippedWarning, labelFromDataverse, columnDisplayName, resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, pageBindingsReport, pageBindingsNote, readPreviousPageKeys, assignPageKeys, missingDownloads, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, fieldSecurityProfileOmissions, fieldSecurityProfilesNote, readAppShellSettings, iconWebResources, readDashboards, readRelationships, droppedSubareaCount, recoverAppSolution, runDownload, writePageTree, generatedFolders, GUARDED_FS_METHODS, preserveAuthoredLanguageCode, makeDownloadSdk, compareText, main };
diff --git a/plugins/model-apps/scripts/lib/chart-verify.js b/plugins/model-apps/scripts/lib/chart-verify.js
new file mode 100644
index 000000000..0a968455d
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/chart-verify.js
@@ -0,0 +1,350 @@
+'use strict';
+// What verify holds a deployed chart's CONTENT to (lib/verify-spec.js, the charts section). The presence check finds the chart; these checks say
+// whether the chart it found is the one the spec describes: its type, the query it draws (table, group-by column, measure), and — where the build
+// owns them — its description and title. A chart that exists with the wrong type, a different grouping or an extra filter used to pass verify;
+// it now fails, for a legacy chart as for a declared one, because verify reports what is deployed, not what a rebuild would repair.
+//
+// The expectation is the build's own:
+// - a declared chart (`reconcile: "declared"`): the intent lib/chart-reconcile.js compileChartIntent compiles — chart type, one Choice
+// category on the chart's table, one count/countcolumn measure of the table's primary id, and the description and title only where the spec
+// sets them to non-blank text;
+// - a legacy chart: what sdk-build.js chartDef sends — chart type, group-by and `measure || 'count'` of the primary id, and the description
+// the build reconciles (#496) where the spec sets one. Its title is not asserted: the legacy build ignores a title (validation warns), and the
+// name chartDef puts in the presentation is not stored by the SDK's scratch presentation, which has no Title element. A legacy measure the
+// verifier does not know as a FetchXML aggregate is not compared (unverified), never failed by the declared validator's narrower rule.
+//
+// The deployed side is the PUBLISHED row (a plain read of savedqueryvisualization answers the published layer; sdk-build.js says so where it
+// reads a description), the same row the presence check found:
+// datadescription, as the SDK writes it (ChartAdapter, scripts/vendor/cds-maker-sdk.cjs):
+// <datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="new_ticket">
+// <attribute alias="agg_0" name="new_ticketid" aggregate="count" />
+// <attribute alias="grp_0" name="new_status" groupby="true" />
+// </entity></fetch></fetchcollection>
+// <categorycollection><category alias="grp_0"><measurecollection><measure alias="agg_0" /></measurecollection></category></categorycollection>
+// </datadefinition>
+// presentationdescription, the chart type on the one Series item, styling around it:
+// <Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas>…</ChartAreas>…</Chart>
+//
+// Both are read with the one strict XML reader (lib/strict-xml.js): an XML declaration or byte order mark, either quote style, any attribute
+// order, `<a/>` or `<a></a>`, character references and white space between elements read the same; a document type declaration, a malformed
+// document, one too large or too deep is not read, and its content is UNVERIFIED — never normalized into a pass.
+//
+// Three outcomes per check, kept apart:
+// - a pass: every part of the query is one this verifier models and each equals the expectation;
+// - a FAILURE: a part the verifier models contradicts the expectation — another chart type, a second measure or series, a different group-by
+// column or date grouping, another aggregate (count and countcolumn are distinct), another table, a filter or a join that changes the rows
+// the chart counts, or a declared title the fully read presentation does not have;
+// - UNVERIFIED: something the verifier cannot give a meaning to — an element or attribute it does not model (an order, an outer join with
+// nothing in it, a per-series chart type), an alias that names nothing, or a document it cannot read. An unknown element is never dropped
+// to obtain a match: the platform's own additions need a measurement before they are let through.
+//
+// Styling — palette, colours, custom properties, axes, legends — is not the spec's, so it is not compared at all: the declared reconcile keeps
+// it byte for byte (chart-reconcile-real-bundle.test.js), which is an ownership boundary, not evidence that the platform rewrites it.
+//
+// Nothing here reads the service or writes anything: it is handed the row verify read.
+
+const { readXmlElements, XML_PREDEFINED } = require('./strict-xml.js');
+const { isDeclaredChart, compileChartIntent, CHART_TYPES } = require('./chart-reconcile.js');
+
+// The datadescription and presentationdescription of a chart the build makes are a few hundred characters; a maker-styled one a few
+// kilobytes. Anything past these bounds is not a chart this verifier reads (and a deep one would cost the reader the square of its depth).
+const MAX_CHART_XML = 256 * 1024;
+const MAX_CHART_DEPTH = 32;
+// The FetchXML aggregates (https://learn.microsoft.com/en-us/power-apps/developer/data-platform/fetchxml/aggregate-data). A legacy chart's
+// measure is sent as written (chartDef), so only one of these, written as FetchXML writes it, has a meaning the verifier can compare.
+const FETCH_AGGREGATES = ['count', 'countcolumn', 'sum', 'avg', 'min', 'max'];
+
+const lc = (s) => String(s == null ? '' : s).toLowerCase();
+
+const DATA = 'datadefinition';
+const FETCH_PATH = 'datadefinition/fetchcollection/fetch';
+const ENTITY_PATH = `${FETCH_PATH}/entity`;
+const CATEGORY_PATH = 'datadefinition/categorycollection/category';
+// The elements of a datadescription this verifier gives a meaning to, by where they are, with the attributes each may carry. Anything else is
+// unverified. A filter, a join and an order are handled apart (below), because what they mean is known.
+const KNOWN_DATA = new Map([
+ ['|datadefinition', []],
+ ['datadefinition|fetchcollection', []],
+ ['datadefinition/fetchcollection|fetch', ['mapping', 'aggregate']],
+ [`${FETCH_PATH}|entity`, ['name']],
+ [`${ENTITY_PATH}|attribute`, ['name', 'alias', 'aggregate', 'groupby', 'dategrouping']],
+ ['datadefinition|categorycollection', []],
+ ['datadefinition/categorycollection|category', ['alias']],
+ [`${CATEGORY_PATH}|measurecollection`, []],
+ [`${CATEGORY_PATH}/measurecollection|measure`, ['alias']],
+]);
+
+/**
+ * What the spec says the chart is, as the build compiles it, or `{ unverifiable }` when it cannot be compiled into something to compare.
+ * `aggregate` is null for a legacy measure the verifier does not know (its data check is then unverified).
+ * @returns {{ declared: boolean, entity: string, chartType: string|null, groupBy: string, measureAttribute: string, aggregate: string|null,
+ * measure: *, description?: string, title?: string } | { declared: boolean, unverifiable: string }}
+ */
+function expectedChart(ch) {
+ const declared = isDeclaredChart(ch);
+ if (declared) {
+ const { errors, intent } = compileChartIntent(ch);
+ if (errors.length) return { declared, unverifiable: `the declared chart does not compile (${errors.join('; ')})` };
+ return {
+ declared,
+ entity: intent.entity,
+ chartType: intent.chartType,
+ groupBy: intent.category.attribute,
+ measureAttribute: intent.series.attribute,
+ aggregate: intent.series.aggregate,
+ measure: intent.series.aggregate,
+ ...(intent.description !== undefined ? { description: intent.description } : {}),
+ ...(intent.title !== undefined ? { title: intent.title } : {}),
+ };
+ }
+ const entity = lc(ch && ch.entity);
+ const groupBy = lc(ch && ch.groupBy);
+ if (!entity || !groupBy) return { declared, unverifiable: 'the chart names no table or no group-by column' };
+ // chartDef sends `ch.measure || 'count'` as the aggregate, exactly as written.
+ const measure = (ch && ch.measure) || 'count';
+ const out = {
+ declared,
+ entity,
+ chartType: CHART_TYPES.includes(ch.chartType) ? ch.chartType : null,
+ groupBy,
+ measureAttribute: `${entity}id`,
+ aggregate: typeof measure === 'string' && FETCH_AGGREGATES.includes(measure) ? measure : null,
+ measure,
+ };
+ // The legacy build writes a description only when the spec sets one (sdk-build.js, "Same two guards as views").
+ if (typeof ch.description === 'string' && ch.description.trim()) out.description = ch.description.trim();
+ return out;
+}
+
+function readChartXml(xml, what, options) {
+ if (typeof xml !== 'string' || !xml.trim()) return { unreadable: `the chart has no ${what} to read` };
+ if (xml.length > MAX_CHART_XML) return { unreadable: `its ${what} is larger than the verifier reads` };
+ const read = readXmlElements(xml, () => true, { maxDepth: MAX_CHART_DEPTH, ...options });
+ if (!read.ok) return { unreadable: `its ${what} is not XML the verifier reads (${read.detail})` };
+ return { elements: read.elements };
+}
+
+const within = (path, base) => path === base || path.startsWith(`${base}/`);
+
+/**
+ * The verdict on the query a chart draws: `{ verdict: 'pass'|'fail'|'unverified', detail }`. A known contradiction fails even when another part
+ * is unknown: two measures are two measures whatever else the document holds.
+ */
+function chartDataVerdict(xml, want) {
+ // Every element of a datadescription holds elements only: text, a comment or a CDATA section anywhere in it is not read.
+ const doc = readChartXml(xml, 'datadescription', { elementOnly: () => true });
+ if (doc.unreadable) return { verdict: 'unverified', detail: doc.unreadable };
+ const contradictions = [];
+ const unknowns = [];
+ const note = (list, text) => { if (!list.includes(text)) list.push(text); };
+ const roots = doc.elements.filter((e) => e.path === '');
+ if (roots.length !== 1 || roots[0].name !== DATA) return { verdict: 'unverified', detail: 'its datadescription is not a datadefinition' };
+ // A filter or a join is read as one thing, its content with it: elements under one are not separately unknown.
+ const covered = [];
+ const fetches = [];
+ const entities = [];
+ const attributes = [];
+ const categories = [];
+ const measures = [];
+ for (const e of doc.elements) {
+ if (covered.some((base) => within(e.path, base))) continue;
+ if (within(e.path, ENTITY_PATH) && e.name === 'filter') {
+ note(contradictions, 'a filter narrows the rows it counts, which the spec\u2019s chart does not');
+ covered.push(`${e.path}/filter`);
+ continue;
+ }
+ if (within(e.path, ENTITY_PATH) && e.name === 'link-entity') {
+ const self = `${e.path}/link-entity`;
+ const holds = doc.elements.some((x) => within(x.path, self));
+ // An outer join that brings nothing in and filters nothing does not change the rows counted, but what the platform does with one in a
+ // chart is not measured: unverified. Any other join (an inner one changes the rows; one that holds a column moves the measure or the
+ // category to another table) contradicts the spec's base-table chart.
+ if (lc(e.attrs['link-type']) === 'outer' && !holds) note(unknowns, `an outer join to ${e.attrs.name || 'a table'}`);
+ else note(contradictions, `it joins ${e.attrs.name || 'another table'}, which the spec\u2019s chart does not`);
+ covered.push(self);
+ continue;
+ }
+ if (e.path === ENTITY_PATH && e.name === 'order') { note(unknowns, 'an order on its groups'); continue; }
+ const allowed = KNOWN_DATA.get(`${e.path}|${e.name}`);
+ if (!allowed) { note(unknowns, `an element <${e.name}> the verifier does not model`); continue; }
+ for (const a of Object.keys(e.attrs)) if (!allowed.includes(a)) note(unknowns, `the attribute ${a} on <${e.name}>`);
+ if (e.name === 'fetch') fetches.push(e);
+ else if (e.name === 'entity') entities.push(e);
+ else if (e.name === 'attribute') attributes.push(e);
+ else if (e.name === 'category') categories.push(e);
+ else if (e.name === 'measure') measures.push(e);
+ }
+ if (fetches.length !== 1) note(unknowns, `${fetches.length} fetches`);
+ for (const f of fetches) {
+ if (f.attrs.mapping !== undefined && f.attrs.mapping !== 'logical') note(unknowns, `a fetch with mapping "${f.attrs.mapping}"`);
+ if (lc(f.attrs.aggregate) !== 'true') note(unknowns, 'a fetch that is not an aggregate query');
+ }
+ if (entities.length !== 1) note(unknowns, `${entities.length} entities in its fetch`);
+ for (const en of entities) if (lc(en.attrs.name) !== want.entity) note(contradictions, `it reads ${en.attrs.name || 'no table'}, not ${want.entity}`);
+ // The aliases are the references between the query and its category collection; a document where two columns share one cannot be mapped.
+ const aliases = attributes.map((a) => a.attrs.alias).filter((a) => a !== undefined);
+ if (new Set(aliases).size !== aliases.length) note(unknowns, 'two columns with one alias');
+ const groups = [];
+ const aggregates = [];
+ for (const a of attributes) {
+ const isGroup = lc(a.attrs.groupby) === 'true';
+ if (a.attrs.aggregate !== undefined && isGroup) note(unknowns, `a column ${a.attrs.name || ''} that is both grouped and aggregated`);
+ else if (a.attrs.aggregate !== undefined) aggregates.push(a);
+ else if (isGroup) groups.push(a);
+ else note(unknowns, `a column ${a.attrs.name || ''} that is neither grouped nor aggregated`);
+ }
+ if (aggregates.length === 0) note(contradictions, 'it has no measure');
+ else if (aggregates.length > 1) note(contradictions, `it has ${aggregates.length} measures; the spec\u2019s chart has one`);
+ if (groups.length === 0) note(contradictions, 'it has no category');
+ else if (groups.length > 1) note(contradictions, `it groups by ${groups.length} columns; the spec\u2019s chart groups by one`);
+ if (aggregates.length === 1) {
+ const m = aggregates[0];
+ if (lc(m.attrs.name) !== want.measureAttribute) note(contradictions, `its measure is on ${m.attrs.name || 'no column'}, not ${want.measureAttribute}`);
+ if (want.aggregate === null) note(unknowns, `the spec\u2019s measure ${JSON.stringify(want.measure)} is not an aggregate the verifier compares`);
+ // FetchXML writes an aggregate in lower case; one written otherwise is not known to mean the same.
+ else if (m.attrs.aggregate === want.aggregate) { /* the measure the spec asks for */ }
+ else if (lc(m.attrs.aggregate) === want.aggregate) note(unknowns, `the aggregate "${m.attrs.aggregate}"`);
+ else note(contradictions, `it aggregates with ${m.attrs.aggregate}, not ${want.aggregate}`);
+ }
+ if (groups.length === 1) {
+ const g = groups[0];
+ if (lc(g.attrs.name) !== want.groupBy) note(contradictions, `it groups by ${g.attrs.name || 'no column'}, not ${want.groupBy}`);
+ if (g.attrs.dategrouping !== undefined) note(contradictions, `it groups ${g.attrs.name || 'its column'} by ${g.attrs.dategrouping}, which a Choice group-by does not`);
+ }
+ if (categories.length === 0) note(unknowns, 'no category in its category collection');
+ else if (categories.length > 1) note(contradictions, `it has ${categories.length} categories; the spec\u2019s chart has one`);
+ if (categories.length === 1) {
+ const cat = categories[0];
+ if (groups.length === 1 && (cat.attrs.alias === undefined || cat.attrs.alias !== groups[0].attrs.alias)) note(unknowns, 'a category that does not name its group-by column');
+ if (measures.length === 0) note(unknowns, 'a category with no measure');
+ else if (measures.length > 1) note(contradictions, `it shows ${measures.length} series; the spec\u2019s chart shows one`);
+ else if (aggregates.length === 1 && (measures[0].attrs.alias === undefined || measures[0].attrs.alias !== aggregates[0].attrs.alias)) note(unknowns, 'a series that does not name its measure');
+ }
+ if (contradictions.length) return { verdict: 'fail', detail: contradictions.join('; ') };
+ if (unknowns.length) return { verdict: 'unverified', detail: `its query holds what the verifier does not model: ${unknowns.join('; ')}` };
+ return { verdict: 'pass', detail: '' };
+}
+
+// The text of an element the strict reader placed (`spans`), as an XML parser gives its textContent; null when it holds markup (a child element,
+// a comment, a CDATA section), which this does not read. References are decoded (the reader has checked each is a predefined entity or a
+// character XML allows) and line ends read as XML reads them (https://www.w3.org/TR/xml/#sec-line-ends).
+function elementText(xml, el) {
+ const whole = xml.slice(el.start, el.end);
+ let quote = '';
+ let close = -1;
+ for (let i = 1; i < whole.length; i += 1) {
+ const c = whole[i];
+ if (quote) {
+ if (c === quote) quote = '';
+ } else if (c === '"' || c === '\'') {
+ quote = c;
+ } else if (c === '>') {
+ close = i;
+ break;
+ }
+ }
+ if (close < 0) return null;
+ if (whole[close - 1] === '/') return '';
+ const inner = whole.slice(close + 1, whole.lastIndexOf('</'));
+ if (inner.includes('<')) return null;
+ return inner.replace(/\r\n?/g, '\n').replace(/&(?:#x([0-9a-fA-F]+)|#([0-9]+)|(lt|gt|amp|quot|apos));/g, (ref, hex, dec, name) => (name
+ ? XML_PREDEFINED[name]
+ : String.fromCodePoint(parseInt(hex !== undefined ? hex : dec, hex !== undefined ? 16 : 10))));
+}
+
+/**
+ * The verdicts on a chart's presentation: its type (from the one Series item's ChartType, which is where the SDK reads and writes it) and,
+ * when `want.title` is set, its title (the first Title element's text, as the SDK reads it).
+ * @returns {{ type: { verdict, detail }, title?: { verdict, detail } }}
+ */
+function chartPresentationVerdicts(xml, want) {
+ const doc = readChartXml(xml, 'presentationdescription', { spans: true });
+ const out = {};
+ if (doc.unreadable) {
+ out.type = { verdict: 'unverified', detail: doc.unreadable };
+ if (want.title !== undefined) out.title = { verdict: 'unverified', detail: doc.unreadable };
+ return out;
+ }
+ const roots = doc.elements.filter((e) => e.path === '');
+ if (roots.length !== 1 || roots[0].name !== 'Chart') {
+ out.type = { verdict: 'unverified', detail: 'its presentationdescription is not a Chart' };
+ if (want.title !== undefined) out.title = { verdict: 'unverified', detail: 'its presentationdescription is not a Chart' };
+ return out;
+ }
+ const items = doc.elements.filter((e) => e.name === 'Series' && e.path === 'Chart/Series');
+ const typedElsewhere = doc.elements.some((e) => e.name === 'Series' && e.path !== 'Chart/Series' && e.attrs.ChartType !== undefined);
+ if (want.chartType === null) out.type = { verdict: 'unverified', detail: 'the spec\u2019s chartType is not one the build writes' };
+ else if (items.length > 1) out.type = { verdict: 'fail', detail: `it presents ${items.length} series; the spec\u2019s chart presents one` };
+ else if (items.length === 0) out.type = { verdict: 'unverified', detail: 'its presentation has no series' };
+ else if (typedElsewhere) out.type = { verdict: 'unverified', detail: 'its presentation sets a chart type outside its series' };
+ else if (items[0].attrs.ChartType === undefined) out.type = { verdict: 'unverified', detail: 'its series states no chart type' };
+ // The SDK reads ChartType case-insensitively (its known types), so the verifier does too.
+ else if (lc(items[0].attrs.ChartType) === lc(want.chartType)) out.type = { verdict: 'pass', detail: '' };
+ else out.type = { verdict: 'fail', detail: `it is a ${items[0].attrs.ChartType} chart, not ${want.chartType}` };
+ if (want.title !== undefined) {
+ const titles = doc.elements.filter((e) => e.name === 'Title');
+ if (titles.length === 0) out.title = { verdict: 'fail', detail: `the chart has no title element, so the declared title "${want.title}" is not shown` };
+ else if (titles.length > 1) out.title = { verdict: 'unverified', detail: 'its presentation has more than one title' };
+ else {
+ const text = elementText(xml, titles[0]);
+ if (text === null) out.title = { verdict: 'unverified', detail: 'its title holds markup the verifier does not read' };
+ else if (text.trim() === want.title) out.title = { verdict: 'pass', detail: '' };
+ else out.title = { verdict: 'fail', detail: `its title is "${text.trim()}", not "${want.title}"` };
+ }
+ }
+ return out;
+}
+
+// A legacy chart's definition is left as it is by a rebuild (sdk-build.js charts phase), so a mismatch there says how to change it.
+const LEGACY_NOTE = ' (the chart is not reconcile: "declared", so a rebuild leaves an existing chart\u2019s definition as it is: declare it, or recreate the chart, to change it)';
+
+/**
+ * The content checks of one present chart. `row` is the published row verify read, with datadescription, presentationdescription and
+ * description. A row that carries neither XML column comes from a reader that does not read chart content: its presence is not proof of
+ * what it holds, so its type and query (and a declared title) are named unverified, never passed, and a declared description is still
+ * checked when the row carries one.
+ * @param {object} ch the spec chart
+ * @param {object} row the deployed row
+ * @param {string} name the name the chart's checks report under (the presence check's)
+ * @returns {{ checks: { kind: string, name: string, present: boolean, detail: string }[], unverified: string[] }}
+ */
+function chartContentChecks(ch, row, name) {
+ const checks = [];
+ const unverified = [];
+ const has = (k) => !!row && Object.prototype.hasOwnProperty.call(row, k);
+ const contentFree = !has('datadescription') && !has('presentationdescription');
+ const want = expectedChart(ch);
+ if (want.unverifiable) {
+ unverified.push(`chart-data:${name} (${want.unverifiable})`);
+ return { checks, unverified };
+ }
+ const report = (kind, v, legacyNote) => {
+ if (v.verdict === 'pass') checks.push({ kind, name, present: true, detail: '' });
+ else if (v.verdict === 'fail') checks.push({ kind, name, present: false, detail: `${v.detail}${legacyNote && !want.declared ? LEGACY_NOTE : ''}` });
+ else unverified.push(`${kind}:${name} (${v.detail})`);
+ };
+ let presentation = {};
+ if (contentFree) {
+ const notRead = { verdict: 'unverified', detail: 'the read does not carry the chart\u2019s content' };
+ report('chart-type', notRead);
+ report('chart-data', notRead);
+ if (want.title !== undefined) presentation = { title: notRead };
+ } else {
+ presentation = chartPresentationVerdicts(has('presentationdescription') ? row.presentationdescription : undefined, want);
+ report('chart-type', presentation.type, true);
+ report('chart-data', chartDataVerdict(has('datadescription') ? row.datadescription : undefined, want), true);
+ }
+ if (want.description !== undefined) {
+ if (!has('description')) report('chart-description', { verdict: 'unverified', detail: 'the read does not carry the chart\u2019s description' });
+ else {
+ // Compared trimmed on both sides: a chart created from an untrimmed description stores it as written (chartDef), and the build's
+ // own reconcile compares the trimmed text.
+ const got = row.description == null ? '' : String(row.description).trim();
+ report('chart-description', got === want.description ? { verdict: 'pass' } : { verdict: 'fail', detail: got ? `its description is "${got}", not the spec\u2019s` : 'it has no description; the spec sets one' });
+ }
+ }
+ if (presentation.title) report('chart-title', presentation.title);
+ return { checks, unverified };
+}
+
+module.exports = { expectedChart, chartDataVerdict, chartPresentationVerdicts, chartContentChecks, MAX_CHART_XML };
diff --git a/plugins/model-apps/scripts/lib/configuration-artifacts.js b/plugins/model-apps/scripts/lib/configuration-artifacts.js
index 0e81f02c9..266d865f6 100644
--- a/plugins/model-apps/scripts/lib/configuration-artifacts.js
+++ b/plugins/model-apps/scripts/lib/configuration-artifacts.js
@@ -1629,6 +1629,15 @@ function connectorName(value) {
return match ? match[1] : text;
}
+// The binding a page's gate reads for one connection reference whose row a caller read itself (the managed download's restore,
+// lib/configuration-protected.js restoreProofOf): 'bound', 'unbound' or 'unknown', from the same definition (observe) as every
+// build's, so a restore cannot call ready what a rebuild would stop on. `row` is { connectionId, connectorId } as the row holds them,
+// `entry` the reference's App Spec declaration, and `inventory` what connectionInventory answers (a Map, or null when unread). Only
+// the verdict leaves: the connection id is compared in memory.
+function referenceBinding(row, entry, inventory) {
+ return observe('connectionReference', '', null, entry, row, 'plan-read', inventory).binding;
+}
+
// The connections a binding can be proven against: a Map of lower-cased connection id -> connector name (null
// when the row does not say), read once per run through `ctx.connections()` (the caller's inventory reader, rows
// as list-connections.js answers them: { connectionId, connectorId, displayName }). Without a reader, or when the
@@ -3252,6 +3261,10 @@ module.exports = {
hasConfigurationDefinitions,
configurationReadiness,
observeConfiguration,
+ // A page's readiness of one connection reference, for the managed download's restore (lib/configuration-protected.js
+ // restoreProofOf): the connection inventory reader and the binding verdict every build's page gate uses.
+ connectionInventory,
+ referenceBinding,
configurationPageBlockers,
configurationContext,
configurationDestructive,
diff --git a/plugins/model-apps/scripts/lib/configuration-build.js b/plugins/model-apps/scripts/lib/configuration-build.js
index dbc38d6be..ea862789e 100644
--- a/plugins/model-apps/scripts/lib/configuration-build.js
+++ b/plugins/model-apps/scripts/lib/configuration-build.js
@@ -243,4 +243,4 @@ function createConfigurationRuntime({ spec, sdk, provision, opts = {}, appUnique
};
}
-module.exports = { createConfigurationRuntime, sweepPendingConfiguration };
+module.exports = { createConfigurationRuntime, sweepPendingConfiguration, namedByPages };
diff --git a/plugins/model-apps/scripts/lib/configuration-create-bindings.js b/plugins/model-apps/scripts/lib/configuration-create-bindings.js
index 2b2804c67..df8d76566 100644
--- a/plugins/model-apps/scripts/lib/configuration-create-bindings.js
+++ b/plugins/model-apps/scripts/lib/configuration-create-bindings.js
@@ -1478,4 +1478,7 @@ module.exports = {
observe,
editShapeOf,
projectionOf,
+ semanticOf,
+ readMembers,
+ ruleStateOf,
};
diff --git a/plugins/model-apps/scripts/lib/configuration-protected.js b/plugins/model-apps/scripts/lib/configuration-protected.js
index 568435f02..88e0bf272 100644
--- a/plugins/model-apps/scripts/lib/configuration-protected.js
+++ b/plugins/model-apps/scripts/lib/configuration-protected.js
@@ -1268,6 +1268,122 @@ function protectedVerifyPort({ spec, manifest, dataverse, solution, bindings })
};
}
+/**
+ * The explicit managed download's proof that ONE declaration it rebuilt from the service (lib/declared-configuration-io.js) is the
+ * item its committed binding holds, unchanged, so a rebuild of the downloaded spec sends nothing for it. Read-only, over the same
+ * exact location and judgment the build's preflight uses (locateItem, judgeBoundShape), with no deployment settings (the download
+ * writes none, and a rebuild without them is the no-settings rebuild):
+ * - `spec` holds the candidate declaration and `manifest` is the store's groups in the shape manifestStore reads; the item must be
+ * bound there (committed, nothing pending) at exactly the ids the declaration derives;
+ * - the plan of the candidate must change nothing: no root or child edit, no create, no rule-state change, and no row under the root
+ * the binding does not hold — except, for an environment variable, one value set outside the plugin, which a rebuild without
+ * settings leaves alone (childVerdict) and which is counted, never read;
+ * - the solution must hold every member now (readMembers): a restore never repairs membership;
+ * - every bound row must read back as its committed projection (`consumerRows`, the build's consumer state), computed over the same
+ * fields: the plan of a bound row expects what the row has for every field the declaration omits, so without this a row changed
+ * outside the plugin would be downloaded as if the build had made it so (its drift "refreshed away"). A connection reference's
+ * connected flag is not part of its declaration (which connection is private, and is bound per environment), so either value
+ * proves it.
+ * Answers { ok: true, values, valueFilled, defaultSet, defaultFilled, valueSchemaSet, connected[, binding] } or { ok: false, code } with a code of
+ * lib/managed-restore-report.js. Every flag is read from the rows this proof proved, in this one pass, so what a download says of an
+ * item's readiness is what it proved, never an earlier read a change in between could leave behind:
+ * - `values`: how many value rows a variable has (0 or 1); `valueFilled`: whether that row holds a value the build's readiness
+ * counts; `defaultSet` / `defaultFilled`: whether the variable's definition has a default, and one the readiness counts;
+ * `valueSchemaSet`: whether it has a value schema;
+ * - `connected`: whether a connection reference's row holds a connection id;
+ * - `binding` (only when `connections` is given, the connection inventory reader of configuration-artifacts.js connectionInventory):
+ * the verdict a rebuild's page gate gives the reference ('bound', 'unbound' or 'unknown', configuration-artifacts.js
+ * referenceBinding). A connection id in the row is not that proof: the connection must be in the environment's connections and be
+ * one of the connector the row and the declaration name. Read last, once everything else is proved, so a reference left out for
+ * another reason costs no inventory read.
+ * Only these flags leave: the values themselves are compared in memory and dropped. It sends nothing and never throws for what it reads.
+ */
+async function restoreProofOf({ spec, manifest, dataverse, solution, kind, key, consumerRows, connections }) {
+ const failed = (error) => ({ ok: false, code: error && error.code === B.NOT_FOUND_CODE ? 'missing' : error && error.code === UNVERIFIED_CODE ? 'unread' : 'not-equivalent' });
+ let item;
+ try {
+ const env = await environmentOf({ spec, store: manifestStore(manifest), dataverse, solution, bindings: undefined });
+ item = await locateItem(env, kind, key);
+ } catch (error) {
+ return failed(error);
+ }
+ if (item.state === 'pending') return { ok: false, code: 'pending' };
+ if (item.state !== 'bound') return { ok: false, code: 'invalid' };
+ const { planned } = item;
+ let judged;
+ try {
+ judged = await judgeBoundShape(dataverse, kind, planned);
+ } catch (error) {
+ return failed(error);
+ }
+ if (judged.halt) return { ok: false, code: judged.halt.code === B.NOT_FOUND_CODE ? 'missing' : 'unread' };
+ const { shape } = judged;
+ if (shape.rootChanged || shape.ruleStateChanged || shape.creates.length || shape.labelEdits.length || shape.fixedEdits.length) return { ok: false, code: 'would-change' };
+ const strayValues = kind === 'environmentVariable' ? shape.removals.filter((r) => r.startsWith('environmentVariableValue:')) : [];
+ if (shape.removals.length > strayValues.length) return { ok: false, code: 'changed' };
+ const values = planned.rows.filter((r) => r.kind === 'environmentVariableValue').length + strayValues.length;
+ if (values > 1) return { ok: false, code: 'multiple-values' };
+ let members;
+ try {
+ members = await B.readMembers(dataverse, planned);
+ } catch {
+ return { ok: false, code: 'membership-unknown' };
+ }
+ if (members.some((m) => m.state === 'unknown')) return { ok: false, code: 'membership-unknown' };
+ if (members.some((m) => m.state !== 'present')) return { ok: false, code: 'not-in-solution' };
+ const committed = Array.isArray(consumerRows) ? consumerRows : [];
+ const sameRow = (c, r) => !!c && c.kind === r.kind && c.key === r.key && normalizeGuid(c.id) === r.id;
+ // Whether a variable's value row holds a usable value, as the build's readiness reads it (configuration-artifacts.js observe:
+ // a value that is neither null nor ''). Only this flag leaves here: the value itself is compared in memory and dropped.
+ let valueFilled = false;
+ const root = { defaultSet: false, defaultFilled: false, valueSchemaSet: false, connected: false };
+ const filledValue = (read) => !!read.decoded.private && read.decoded.private.present && read.decoded.private.value != null && read.decoded.private.value !== '';
+ // The connection reference's row as the binding verdict reads it, in memory only (its connection id never leaves this function).
+ let referenceRow = null;
+ for (const r of planned.rows) {
+ const c = committed.find((x) => sameRow(x, r));
+ if (!c) return { ok: false, code: 'changed' };
+ const read = await B.readConfigurationRow(dataverse, r.kind, r.id);
+ if (read.state === 'absent') return { ok: false, code: 'missing' };
+ if (read.state !== 'present') return { ok: false, code: 'unread' };
+ if (r.kind === 'environmentVariableValue' && filledValue(read)) valueFilled = true;
+ if (r.kind === 'environmentVariable') {
+ const { defaultValue, valueSchema } = read.decoded.fields;
+ root.defaultSet = defaultValue != null;
+ root.defaultFilled = defaultValue != null && defaultValue !== '';
+ root.valueSchemaSet = valueSchema != null;
+ }
+ if (r.kind === 'connectionReference') {
+ root.connected = filledValue(read);
+ referenceRow = { connectionId: root.connected ? read.decoded.private.value : null, connectorId: read.decoded.fields.connectorId };
+ }
+ const semantic = B.semanticOf(r.kind, read.decoded);
+ const variants = r.kind === 'connectionReference' ? [{ ...semantic, connected: false }, { ...semantic, connected: true }] : [semantic];
+ const proved = variants.some((s) => B.projectionOf(r.kind, r.expected, s, read.decoded.unmodelled, [], read.decoded.preserved) === c.projectionSha256);
+ if (!proved) return { ok: false, code: 'changed' };
+ }
+ // A committed row the plan does not hold is a child the declaration no longer derives: the graph changed. A variable's committed
+ // value removed outside the plugin is the one exception — it held nothing a declaration says, and its absence is counted above.
+ for (const c of committed) {
+ if (c.kind === 'environmentVariableValue') continue;
+ if (!planned.rows.some((r) => sameRow(c, r))) return { ok: false, code: 'changed' };
+ }
+ // A value set outside the plugin ('environmentVariableValue:<id>', one at most by now) counts as the build's readiness counts it.
+ for (const stray of strayValues) {
+ const read = await B.readConfigurationRow(dataverse, 'environmentVariableValue', stray.slice(stray.indexOf(':') + 1));
+ if (read.state === 'absent') continue;
+ if (read.state !== 'present') return { ok: false, code: 'unread' };
+ if (filledValue(read)) valueFilled = true;
+ }
+ if (kind === 'connectionReference' && typeof connections === 'function' && referenceRow) {
+ const entry = (Array.isArray(spec.connectionReferences) ? spec.connectionReferences : [])
+ .find((e) => e && String(e.logicalName).toLowerCase() === String(key).toLowerCase());
+ // An unbound row needs no inventory: the verdict is 'unbound' whatever the environment holds.
+ root.binding = A.referenceBinding(referenceRow, entry, referenceRow.connectionId ? await connections() : null);
+ }
+ return { ok: true, values, valueFilled, ...root };
+}
+
module.exports = {
EDIT_CODE,
OPT_IN_CODE,
@@ -1280,5 +1396,7 @@ module.exports = {
preflightProtectedConfiguration,
protectedConfigurationPort,
protectedVerifyPort,
+ restoreProofOf,
+ slotOf,
createProtectedConfiguration,
};
diff --git a/plugins/model-apps/scripts/lib/declared-chart-io.js b/plugins/model-apps/scripts/lib/declared-chart-io.js
new file mode 100644
index 000000000..3b73a55c2
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/declared-chart-io.js
@@ -0,0 +1,158 @@
+'use strict';
+// The explicit managed download's restore of declared charts (charts[].reconcile "declared", createIdentity "stable-v1"): each chart a
+// committed chart group of the build's binding store proves this app CREATED is written back into charts[] as a declaration that
+// rebuilds it exactly, and every other is named. Nothing here writes, binds or publishes. It follows lib/declared-view-io.js; what
+// differs is what a chart declaration can say and how that is proved.
+//
+// What a chart declaration can say (lib/chart-reconcile.js compileChartIntent): a chart type, ONE group-by column of the chart's own
+// table, ONE count or countcolumn measure of the table's primary id, and a description and title. The typed chart the SDK reads
+// (liveFull) shows the category and series but not the rest of the query, so the projection hash alone cannot prove a chart has
+// nothing more: a filter, a join or an order sits in the datadescription the typed chart does not show. So the PUBLISHED row (the
+// one whose layer hash equals the saved one's) is checked with verify's own content checks (lib/chart-verify.js chartContentChecks)
+// against the declaration: every one must pass. A filter, a join, an order, a second series, a date grouping, a related category or
+// an element the verifier does not model leaves the chart out (`unsupported`), never approximated.
+//
+// The shape it writes: the chart's current table and name, `reconcile: "declared"`, chartType, groupBy, the measure stated
+// explicitly, and the description and title only when they hold non-blank text. No chart id and no key: a chart declaration has
+// neither, so the rebuild finds the row through the binding store's key (`<table>/<trimmed name>`), which must be the key the group
+// was bound under (a renamed chart is `key-mismatch`, never rekeyed). A restore is therefore an edit snapshot for THIS build folder:
+// the store selects the exact row, and a same-named chart on the table is never bound in its place. Styling (palette, colours,
+// axes, legends) is not the spec's: a rebuild that changes nothing keeps it byte for byte, which is not a claim that it is portable.
+const { normalizeGuid, projectionBaseline, canonicalJson } = require('./reconcile-common.js');
+const { readManagedFormFile } = require('./declared-form-io.js');
+const { readSavedQueryLayerRows } = require('./savedquery-published.js');
+const { omission, solutionMembershipCheck } = require('./managed-restore-report.js');
+const chartReconcile = require('./chart-reconcile.js');
+const { chartContentChecks } = require('./chart-verify.js');
+const { compareVersions, isPluginVersion, CREATE_IDENTITY_MIN_VERSION } = require('./app-spec.js');
+
+const FAMILY = 'chart';
+// A chart's solution component type (Saved Query Visualization).
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/solutioncomponent
+const CHART_COMPONENT = 59;
+const SETTLED = new Set(['confirmed', 'not-needed']);
+const lc = (v) => String(v == null ? '' : v).toLowerCase();
+const isNotFound = (err) => !!err && (err.statusCode === 404 || err.status === 404);
+const nonBlank = (s) => typeof s === 'string' && s.trim() !== '';
+
+/**
+ * The declaration that rebuilds `chart` (a typed chart the SDK read, types/chart.ts), or { unsupported: why }. Pure: it reads only
+ * `chart`. It covers the typed parts only; restoreManagedCharts proves the rest of the query with the verifier and the planner.
+ */
+function chartDeclarationFromLive(chart) {
+ if (!chart || typeof chart !== 'object' || typeof chart.entityLogicalName !== 'string' || !nonBlank(chart.name)) return { unsupported: 'no table or name' };
+ const live = chartReconcile.liveFull(chart);
+ if (!live) return { unsupported: 'several series or categories, or a measure on a joined table' };
+ const entity = lc(chart.entityLogicalName);
+ if (!chartReconcile.CHART_TYPES.includes(live.chartType)) return { unsupported: 'a chart type a declaration cannot say' };
+ if (live.category.relatedEntity || live.category.dateGrouping) return { unsupported: 'a category on a joined table or grouped by date' };
+ if (!live.category.attribute) return { unsupported: 'a category with no column' };
+ if (live.series.attribute !== `${entity}id`) return { unsupported: 'a measure on another column than the table\'s id' };
+ if (!['count', 'countcolumn'].includes(live.series.aggregate)) return { unsupported: 'a measure that is not a count' };
+ const declaration = { entity, name: chart.name, reconcile: 'declared', chartType: live.chartType, groupBy: live.category.attribute, measure: live.series.aggregate };
+ if (nonBlank(live.description)) declaration.description = live.description;
+ if (nonBlank(live.title)) declaration.title = live.title;
+ return { declaration };
+}
+
+// createIdentity's plugin floor, keeping a higher one the spec already names (the rule of app-components.js setAppThemeFloor).
+const floorOf = (current) => (isPluginVersion(current) && compareVersions(current, CREATE_IDENTITY_MIN_VERSION) > 0 ? current : CREATE_IDENTITY_MIN_VERSION);
+
+/**
+ * The explicit managed download's restore of declared charts (--include-managed --managed-manifest <file>). For each committed chart
+ * group of the store file, in key order, the chart is restored into `spec.charts` (mutated) only when every check holds and the
+ * downloaded spec still validates with it (`validate`, the download's own validator, which also holds the group-by to a Choice
+ * column the spec declares on the chart's table); a restored chart also restores the spec's `createIdentity: "stable-v1"` (only a
+ * stable build keeps chart groups) with its plugin floor. Every other group is answered as an omission with a fixed reason.
+ * The checks, in order: the group is settled and valid; the build created the row; its publish is confirmed or not needed; the row
+ * is read, by its id, on the table its publication names; the app's solution holds it now (a row of its own, or its table held with
+ * all its subcomponents); its projection is the one the build proved; its saved layer equals its
+ * published layer (and the layer the build published); the typed chart inverts (chartDeclarationFromLive); the declaration's key is
+ * the bound key; verify's content checks pass on the published row; the declaration compiles back to the row part for part; and the
+ * build's own planner, given the store's binding, answers noChange for the same row.
+ * Answers { restored: [{ key, id }], omitted: [omission] }; a store file that cannot be used throws `managed-manifest-unusable`.
+ */
+async function restoreManagedCharts({ sdk, spec, file, environment, appUniqueName, solutionUniqueName, validate }) {
+ const { groups, pending, invalid } = readManagedFormFile({ file, environment, appUniqueName, solutionUniqueName }, FAMILY);
+ const inSolution = solutionMembershipCheck({ sdk, solutionUniqueName, componentTypes: [CHART_COMPONENT] });
+ const restored = [];
+ const omitted = [
+ ...pending.map((p) => omission({ kind: 'chart', key: p.key, code: 'pending' })),
+ ...invalid.map((p) => omission({ kind: 'chart', key: p.key, code: 'invalid' })),
+ ];
+ for (const key of [...groups.keys()].sort()) {
+ const group = groups.get(key);
+ const id = normalizeGuid(group.root && group.root.id);
+ const left = (code, name) => omitted.push(omission({ kind: 'chart', id, key, name, code }));
+ const record = id ? (group.records || []).find((r) => r && r.kind === FAMILY && normalizeGuid(r.id) === id) : null;
+ if (!record) { left('invalid'); continue; }
+ if (record.origin !== 'created') { left('not-created'); continue; }
+ const publication = group.publication || {};
+ if (!SETTLED.has(publication.state)) { left('publication-unsettled'); continue; }
+ let art;
+ try {
+ await sdk.fetchArtifact('chart', id, { overwrite: true });
+ art = await sdk.getArtifact('chart', id);
+ } catch (e) {
+ left(isNotFound(e) ? 'missing' : 'unread');
+ continue;
+ }
+ if (!art || typeof art !== 'object') { left('missing'); continue; }
+ const name = typeof art.name === 'string' ? art.name : undefined;
+ const table = lc(publication.scope && publication.scope.table);
+ if (normalizeGuid(art.id) !== id || !table || lc(art.entityLogicalName) !== table) { left('wrong-table', name); continue; }
+ // The store proves the build put the row in the solution once; the solution must still hold it now (lib/managed-restore-report.js).
+ const membership = await inSolution(id, CHART_COMPONENT, table);
+ if (membership) { left(membership, name); continue; }
+ const live = chartReconcile.liveFull(art);
+ if (!live) { left('unsupported', name); continue; }
+ const observed = projectionBaseline(live).intentSha256;
+ const baseline = group.consumerState && group.consumerState.baseline;
+ if (observed !== record.intentSha256 || (baseline && baseline.intentSha256 !== observed)) { left('changed', name); continue; }
+ let layers;
+ try {
+ layers = await readSavedQueryLayerRows(FAMILY, sdk.dataverse, group);
+ } catch {
+ left('unread', name);
+ continue;
+ }
+ if (!layers.published || layers.savedSha256 !== layers.publishedSha256) { left('unpublished-changes', name); continue; }
+ if (publication.state === 'confirmed' && publication.desiredSha256 && publication.desiredSha256 !== layers.savedSha256) { left('changed', name); continue; }
+ const inverse = chartDeclarationFromLive(art);
+ if (!inverse.declaration) { left('unsupported', name); continue; }
+ const declaration = inverse.declaration;
+ if (chartReconcile.declaredChartKey(declaration) !== key) { left('key-mismatch', name); continue; }
+ // Verify's own checks on the published row (lib/chart-verify.js): anything the typed chart does not show — a filter, a join, an
+ // order, an element the verifier does not model — fails or is unverified, and either leaves the chart out.
+ const content = chartContentChecks(declaration, layers.published, key);
+ if (content.unverified.length || !content.checks.length || content.checks.some((c) => !c.present)) { left('unsupported', name); continue; }
+ const { errors, intent } = chartReconcile.compileChartIntent(declaration);
+ const desired = intent && chartReconcile.desiredFull(intent, live);
+ if (errors.length || !desired || chartReconcile.PARTS.some((p) => canonicalJson(desired[p]) !== canonicalJson(live[p]))) { left('not-equivalent', name); continue; }
+ // The build's own planner, given exactly the binding the store holds: a rebuild must answer noChange, bind as it is, and send
+ // nothing. GET only (chart-reconcile.js planChartReconcile).
+ let plan;
+ try {
+ plan = await chartReconcile.planChartReconcile({ chart: declaration, sdk }, {
+ managed: { lookup: async (kind, k) => (kind === FAMILY && k === key ? record : null) },
+ });
+ } catch {
+ left('unread', name);
+ continue;
+ }
+ if (plan.action !== 'noChange' || !plan.bindUnchanged || plan.refused.length || plan.unknown.length || normalizeGuid(plan.chartId) !== id) { left('would-change', name); continue; }
+ const charts = Array.isArray(spec.charts) ? spec.charts : [];
+ const at = charts.findIndex((c) => c && chartReconcile.declaredChartKey(c) === key);
+ const next = at >= 0 ? charts.map((c, i) => (i === at ? declaration : c)) : [...charts, declaration];
+ const candidate = { ...spec, charts: next, createIdentity: 'stable-v1', minimumPluginVersion: floorOf(spec.minimumPluginVersion) };
+ const check = validate(candidate);
+ if (!check || !check.ok) { left('invalid-in-spec', name); continue; }
+ spec.charts = next;
+ spec.createIdentity = candidate.createIdentity;
+ spec.minimumPluginVersion = candidate.minimumPluginVersion;
+ restored.push({ key, id });
+ }
+ return { restored, omitted };
+}
+
+module.exports = { restoreManagedCharts, chartDeclarationFromLive };
diff --git a/plugins/model-apps/scripts/lib/declared-configuration-io.js b/plugins/model-apps/scripts/lib/declared-configuration-io.js
new file mode 100644
index 000000000..61285488b
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/declared-configuration-io.js
@@ -0,0 +1,336 @@
+'use strict';
+// The explicit managed download's restore of protected configuration (configurationIdentity "stable-v1"): each item a committed
+// configuration group of the build's binding store holds is written back into its App Spec list as a declaration that rebuilds as
+// no change, and every other is named. Nothing here writes, binds or publishes.
+//
+// Why this is not a copy of what the build was given. A configuration group keeps no declaration (the binding store records the
+// rows, their ids and the projections the build proved), so the declaration is rebuilt from the rows as they are now, and it is
+// accepted only when the build's own read-only oracle says a rebuild of it changes nothing (configuration-protected.js
+// restoreProofOf): the same exact location, plan and judgment as a build's preflight, and every bound row still reading as the
+// projection the build committed for it. A row changed outside the plugin since is left out rather than downloaded as if the
+// build had made it so.
+//
+// Privacy. These rows can hold values a download must never write: a variable's current value, its default and value schema (they
+// can carry a URL, a key or a tenant's data), a connection reference's connection. They are read here IN MEMORY only, through the
+// exact-id reader (configuration-create-bindings.js readConfigurationRow), never through the SDK's file-backed fetch (which caches
+// the whole row into the workspace). A declaration names only the public fields; a part it leaves out is reported by name
+// (`fields`), never by value, and is never written as a mask, an empty string or a null either: an omitted field is left as it is
+// by a rebuild, while a written null would clear it.
+const { normalizeGuid } = require('./reconcile-common.js');
+const { readManagedFormFile } = require('./declared-form-io.js');
+const B = require('./configuration-create-bindings.js');
+const P = require('./configuration-protected.js');
+const { omission } = require('./managed-restore-report.js');
+const { compareVersions, isPluginVersion } = require('./app-spec.js');
+const { namedByPages } = require('./configuration-build.js');
+const { connectionInventory } = require('./configuration-artifacts.js');
+const { pagesStatingBindings } = require('./page-binding-targets.js');
+
+const IDENTITY = 'stable-v1';
+// The plugin floor of a restored protected item: exact ids, adopted children and the bound-value rules a no-settings rebuild relies
+// on are the ones 2.25.0 ships; an older plugin would plan the same declaration differently.
+const CONFIGURATION_RESTORE_MIN_VERSION = '2.25.0';
+const floorOf = (current) => (isPluginVersion(current) && compareVersions(current, CONFIGURATION_RESTORE_MIN_VERSION) > 0 ? current : CONFIGURATION_RESTORE_MIN_VERSION);
+const lc = (v) => String(v == null ? '' : v).toLowerCase();
+
+// Each restored kind: its App Spec list and the field its store key is made from.
+const LISTS = Object.freeze({
+ environmentVariable: ['environmentVariables', 'schemaName'],
+ connectionReference: ['connectionReferences', 'logicalName'],
+ customApi: ['customApis', 'uniqueName'],
+ duplicateRule: ['duplicateDetectionRules', 'key'],
+});
+
+class Left extends Error {
+ constructor(code, fields) {
+ super(code);
+ this.omitCode = code;
+ if (fields) this.fields = fields;
+ }
+}
+const leave = (code) => { throw new Left(code); };
+
+/**
+ * The store file's configuration groups, read once per restore, as { units: { <kind>: committedUnits }, manifest } — `manifest` in
+ * the shape configuration-protected.js manifestStore reads, holding every configuration kind (a variable's parent is located through
+ * its own group). The file must be this environment's, app's and solution's store (readManagedFormFile); anything else throws
+ * `managed-manifest-unusable`.
+ */
+function readConfigurationStore(args) {
+ const units = {};
+ const manifest = { groups: [], pending: [], invalid: [] };
+ for (const kind of ['environmentVariable', 'connectionReference', 'customApi', 'duplicateRule']) {
+ const u = readManagedFormFile(args, kind);
+ units[kind] = u;
+ for (const [key, g] of u.groups) manifest.groups.push({ family: kind, key, records: g.records, generation: g.generation });
+ for (const p of u.pending) manifest.pending.push({ family: kind, key: p.key });
+ for (const p of u.invalid) manifest.invalid.push({ family: kind, key: p.key });
+ }
+ return { units, manifest };
+}
+
+// One exact-id read, in memory: present, or the omission its answer is.
+async function readRow(dataverse, kind, id) {
+ const got = await B.readConfigurationRow(dataverse, kind, id);
+ if (got.state === 'absent') leave('missing');
+ if (got.state !== 'present') leave('unread');
+ return got;
+}
+
+// The environment variable's declaration from its definition row: schema name, type, labels and required flag, and for a data
+// source its connector, parameter and the parent the store proves. Its default, value schema and value are never written.
+async function declareVariable({ root, key, parentOf }) {
+ const f = root.decoded.fields;
+ if (f.type === 'secret') leave('secret-withheld');
+ if (lc(f.schemaName) !== key) leave('changed');
+ const declaration = { schemaName: f.schemaName, type: f.type };
+ if (f.name != null) declaration.name = f.name;
+ if (f.description != null) declaration.description = f.description;
+ declaration.isRequired = f.isRequired === true;
+ if (f.type === 'dataSource') {
+ if (f.connectorId != null) declaration.connectorId = f.connectorId;
+ if (f.parameterKey != null) declaration.parameterKey = f.parameterKey;
+ }
+ if (f.parentDefinitionId != null) {
+ // Only a data source has a parent an App Spec can name, and only by a variable this download restores at exactly that row.
+ if (f.type !== 'dataSource') leave('unsupported');
+ const parent = await parentOf(f.parentDefinitionId);
+ if (!parent) leave('parent-unproven');
+ declaration.parentSchemaName = parent;
+ }
+ return { declaration, fields: [] };
+}
+
+// A required variable with neither a default nor a value stops a rebuild as incomplete (configuration-artifacts.js
+// runConfigurationStep, ENVIRONMENT_VARIABLE_VALUE_MISSING), so its declaration would not rebuild as no change; a download never fills
+// one in to force a pass. The test is the build's own (observe): a default or a current value that is neither null nor ''.
+// Readiness, and the parts named as withheld, come from the proof's own read (restoreProofOf), never from the read the declaration
+// was built from: a default removed between the two would otherwise be counted from a row the proof no longer saw.
+function acceptVariable({ declaration, proof }) {
+ if (declaration.isRequired && !proof.defaultFilled && !proof.valueFilled) leave('required-value-missing');
+ return [...(proof.defaultSet ? ['defaultValue'] : []), ...(proof.valueSchemaSet ? ['valueSchema'] : [])];
+}
+
+// The pages of the downloaded spec that name each reference and Custom API, as the build's page gate reads them
+// (configuration-build.js beforePages over page-binding-targets.js pagesStatingBindings).
+function namedByPagesOf(spec) {
+ return namedByPages(pagesStatingBindings(spec));
+}
+
+// The connection reference's declaration from its row: logical name, connector, labels. Which connection it is bound to is private
+// and per environment: it is never written, and a rebuild without settings keeps the binding the row has. A reference to a custom
+// connector names that connector by this environment's row id, which a download cannot prove is the same connector anywhere a
+// rebuild runs, so it is left out rather than converted to a shared connector.
+async function declareReference({ root, key }) {
+ const { fields: f, unmodelled, preserved } = root.decoded;
+ if (lc(f.logicalName) !== key) leave('changed');
+ if (f.customConnectorId != null) leave('unsupported-dependency');
+ const declaration = { logicalName: f.logicalName, connectorId: f.connectorId };
+ if (f.name != null) declaration.name = f.name;
+ if (f.description != null) declaration.description = f.description;
+ const fields = [];
+ if (unmodelled.length) fields.push('connectionParameters');
+ if (preserved.promptingbehavior !== undefined) fields.push('promptingBehavior');
+ return { declaration, fields };
+}
+
+// A page that names a reference makes a rebuild gate the page on its binding (CONNECTION_REFERENCE_UNBOUND, or
+// CONNECTION_REFERENCE_BINDING_UNVERIFIED when the connections cannot be read): a plain download declares no reference, so its page is
+// written without that gate, and a restore must not turn that into a stop. So such a reference is restored only when the gate's own
+// verdict is 'bound' (restoreProofOf `binding`, configuration-artifacts.js referenceBinding): its connection is in the environment's
+// connections and is one of its connector. A connection id in the row proves neither, and connections that cannot be read prove
+// nothing. The verdict is taken from the proof's own read, never the earlier read: a connection removed between the two must not count.
+function acceptReference({ key, proof, ctx }) {
+ if (ctx.pagesNaming.references.has(key) && proof.binding !== 'bound') leave('page-unready');
+ return proof.connected ? ['connection'] : [];
+}
+
+// Whether the environment provisions more than one language, read once per download and only when a Custom API is restored:
+// GET /RetrieveProvisionedLanguages() -> { "RetrieveProvisionedLanguages": [1033, 1036] }
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/retrieveprovisionedlanguages
+// A Custom API's labels are localized: its row answers them in one language only, and the other languages' labels need message calls
+// the build does not make (it refuses a label edit on such an environment, CUSTOM_API_LABELS_UNSUPPORTED). They are never written by a
+// download and are named as withheld. A read that fails, or answers a list this cannot read, counts as several: unknown is not one.
+async function severalLanguages(ctx) {
+ if (ctx.severalLanguages === undefined) {
+ let list = null;
+ try {
+ const res = await ctx.dataverse.get('/RetrieveProvisionedLanguages()');
+ const body = res && res.status >= 200 && res.status < 300 ? res.body : null;
+ list = body && Array.isArray(body.RetrieveProvisionedLanguages) ? body.RetrieveProvisionedLanguages : null;
+ } catch {
+ list = null;
+ }
+ ctx.severalLanguages = !(Array.isArray(list) && list.length === 1 && Number.isInteger(list[0]));
+ }
+ return ctx.severalLanguages;
+}
+
+// The Custom API's declaration from its row and its complete bound graph: the root's fixed fields and labels, and both child lists
+// with each child's unique name, type, entity, labels and (a request parameter's) optional flag. Its implementation (the plug-in
+// type) is never authored by an App Spec, and an API that has one is left out whole: what it runs is this environment's code, which
+// the spec cannot carry and a rebuild elsewhere would not have. A scaffold (no implementation) is restored as the scaffold it is.
+async function declareCustomApi({ root, key, children, ctx }) {
+ const { fields: f, preserved } = root.decoded;
+ if (lc(f.uniqueName) !== key) leave('changed');
+ if (preserved._plugintypeid_value != null) leave('implemented');
+ // A page that names an API makes a rebuild gate the page on its implementation (CUSTOM_API_IMPLEMENTATION_UNPROVEN), and a
+ // scaffold has none: declaring it would stop that rebuild before the page a plain download lets it write.
+ if (ctx.pagesNaming.apis.has(key)) leave('page-unready');
+ const declaration = { uniqueName: f.uniqueName };
+ for (const name of ['name', 'displayName', 'description']) if (f[name] != null) declaration[name] = f[name];
+ declaration.binding = f.binding;
+ if (f.boundEntityLogicalName != null) declaration.boundEntityLogicalName = f.boundEntityLogicalName;
+ for (const name of ['isFunction', 'isPrivate', 'allowedProcessingSteps', 'enabledForWorkflow']) declaration[name] = f[name];
+ if (f.executePrivilegeName != null) declaration.executePrivilegeName = f.executePrivilegeName;
+ declaration.requestParameters = [];
+ declaration.responseProperties = [];
+ // Each child by the slot its binding holds it in ('request:<unique name>' / 'response:<unique name>', lower case): a child whose
+ // row now carries another name, or sits in the other direction, is not the child the build bound there.
+ for (const { slot, record, read } of children) {
+ const request = record.kind === 'customApiRequestParameter';
+ if (!request && record.kind !== 'customApiResponseProperty') leave('invalid');
+ const c = read.decoded.fields;
+ if (slot !== `${request ? 'request' : 'response'}:${lc(c.uniqueName)}`) leave('changed');
+ const child = { uniqueName: c.uniqueName, type: c.type };
+ if (c.entityLogicalName != null) child.entityLogicalName = c.entityLogicalName;
+ for (const name of ['name', 'displayName', 'description']) if (c[name] != null) child[name] = c[name];
+ if (request) child.isOptional = c.isOptional === true;
+ (request ? declaration.requestParameters : declaration.responseProperties).push(child);
+ }
+ return { declaration, fields: (await severalLanguages(ctx)) ? ['otherLanguageLabels'] : [] };
+}
+
+const FAMILIES = Object.freeze({
+ environmentVariable: { label: 'environment variable', declare: declareVariable, accept: acceptVariable },
+ connectionReference: { label: 'connection reference', declare: declareReference, accept: acceptReference },
+ customApi: { label: 'Custom API', declare: declareCustomApi },
+ // Withheld as a family: a rule's state (published or not) is part of what a declaration states, and the binding store commits each
+ // row's projection, which holds a rule's fields and conditions but not the state its build left it in. A rule unpublished or
+ // published outside the plugin reads exactly like one its build left that way, so no state a download could state is proved, and
+ // stating the current one would make a change made outside the plugin the spec's. Every committed rule is left out, unread.
+ duplicateRule: { label: 'duplicate rule', withheld: 'state-unproven' },
+});
+
+/**
+ * Restore one committed group: read its root (and, for a family with children, every child its binding holds) in memory, rebuild
+ * the declaration, and accept it only when the protected oracle proves it (restoreProofOf) and the downloaded spec still validates
+ * with it. Throws Left with the omission code otherwise. Answers { declaration, fields }.
+ */
+async function restoreItem(ctx, kind, key, group, extra = {}) {
+ const [list, field] = LISTS[kind];
+ const records = Array.isArray(group.records) ? group.records : [];
+ const rootRecord = records.find((r) => r && r.kind === kind && r.key === key);
+ const id = rootRecord ? normalizeGuid(rootRecord.id) : '';
+ const consumer = group.consumerState;
+ if (!id || !consumer || consumer.version !== 1 || !Array.isArray(consumer.rows)) leave('invalid');
+ const root = await readRow(ctx.dataverse, kind, id);
+ ctx.names.set(`${kind}\u0000${key}`, typeof root.decoded.fields.name === 'string' ? root.decoded.fields.name : undefined);
+ const children = [];
+ for (const r of records) {
+ if (r === rootRecord) continue;
+ const slot = P.slotOf(r);
+ if (slot === null || !r || normalizeGuid(r.id) === '') leave('invalid');
+ // A variable's value row holds nothing a declaration says; restoreProofOf accounts for it without its content.
+ if (r.kind === 'environmentVariableValue') continue;
+ children.push({ slot, record: r, read: await readRow(ctx.dataverse, r.kind, normalizeGuid(r.id)) });
+ }
+ const { declaration, fields } = await FAMILIES[kind].declare({ root, key, children, group, ctx, ...extra });
+ const spec = ctx.spec;
+ const candidate = {
+ ...spec,
+ [list]: [...(Array.isArray(spec[list]) ? spec[list] : []), declaration],
+ configurationIdentity: IDENTITY,
+ minimumPluginVersion: floorOf(spec.minimumPluginVersion),
+ };
+ // The connections are read (once per download) only for a reference a page names: no other restore depends on them.
+ const pageReference = kind === 'connectionReference' && ctx.pagesNaming.references.has(key);
+ const proof = await P.restoreProofOf({
+ spec: candidate, manifest: ctx.manifest, dataverse: ctx.dataverse, solution: ctx.solutionUniqueName, kind, key: declaration[field], consumerRows: consumer.rows,
+ ...(pageReference ? { connections: ctx.inventory } : {}),
+ });
+ if (!proof.ok) leave(proof.code);
+ const accepted = FAMILIES[kind].accept ? FAMILIES[kind].accept({ key, declaration, proof, ctx }) : [];
+ const check = ctx.validate(candidate);
+ if (!check || !check.ok) leave('invalid-in-spec');
+ spec[list] = candidate[list];
+ spec.configurationIdentity = candidate.configurationIdentity;
+ spec.minimumPluginVersion = candidate.minimumPluginVersion;
+ return { id, declaration, fields: [...accepted, ...fields, ...(proof.values ? ['value'] : [])] };
+}
+
+/**
+ * The restore of one configuration kind into `ctx.spec` (mutated), every committed group in key order (a data-source variable after
+ * the parent it names). Answers { restored: [{ key, id }], omitted: [omission], withheld: [omission] }: `withheld` names an item that
+ * WAS restored without some of its parts (`fields`, never their values); it is not an omitted item.
+ */
+async function restoreKind(ctx, kind) {
+ const { groups, pending, invalid } = ctx.units[kind];
+ const label = FAMILIES[kind].label;
+ const restored = [];
+ const omitted = [
+ ...pending.map((p) => omission({ kind: label, key: p.key, code: 'pending' })),
+ ...invalid.map((p) => omission({ kind: label, key: p.key, code: 'invalid' })),
+ ];
+ const withheld = [];
+ const done = new Map();
+ const rootIdOf = (g) => {
+ const r = (g.records || []).find((x) => x && x.kind === kind);
+ return r ? normalizeGuid(r.id) : '';
+ };
+ if (FAMILIES[kind].withheld) {
+ for (const key of [...groups.keys()].sort()) omitted.push(omission({ kind: label, id: rootIdOf(groups.get(key)), key, code: FAMILIES[kind].withheld }));
+ return { restored, omitted, withheld };
+ }
+ const keyByRootId = new Map([...groups].map(([k, g]) => [rootIdOf(g), k]));
+ // Depth-first so a parent variable is restored (and validated) before the child that names it. A key met again while its own
+ // restore is still running is a parent cycle: neither end is proved.
+ const visit = async (key) => {
+ if (done.has(key)) return done.get(key);
+ done.set(key, null);
+ const group = groups.get(key);
+ const parentOf = async (parentId) => {
+ const parentKey = keyByRootId.get(normalizeGuid(parentId));
+ return parentKey ? visit(parentKey) : null;
+ };
+ let result = null;
+ try {
+ const got = await restoreItem(ctx, kind, key, group, { parentOf });
+ restored.push({ key, id: got.id });
+ if (got.fields.length) withheld.push(omission({ kind: label, id: got.id, key, name: ctx.names.get(`${kind}\u0000${key}`), fields: got.fields, code: 'fields-withheld' }));
+ result = got.declaration[LISTS[kind][1]];
+ } catch (e) {
+ if (!(e instanceof Left)) throw e;
+ omitted.push(omission({ kind: label, id: rootIdOf(group), key, name: ctx.names.get(`${kind}\u0000${key}`), code: e.omitCode }));
+ }
+ done.set(key, result);
+ return result;
+ };
+ for (const key of [...groups.keys()].sort()) await visit(key);
+ return { restored, omitted, withheld };
+}
+
+/**
+ * The explicit managed download's restore of protected configuration (--include-managed --managed-manifest <file>): environment
+ * variables, then connection references, then Custom APIs; every duplicate rule is left out unread (state-unproven, FAMILIES).
+ * A restored item also sets the spec's `configurationIdentity: "stable-v1"` (only a protected build keeps these groups, so the store
+ * itself is the proof of the regime) with its plugin floor. Answers { environmentVariables, connectionReferences, customApis,
+ * duplicateDetectionRules } (restoreKind's shape each); a store file that cannot be used throws `managed-manifest-unusable` (readManagedFormFile).
+ * `connections` reads the environment's connections (rows as list-connections.js answers them), the reader a build is given: without
+ * one, or when it fails, a reference a page names is not proved ready and is left out (`page-unready`). Read only, in memory.
+ */
+async function restoreManagedConfiguration({ sdk, spec, file, environment, appUniqueName, solutionUniqueName, validate, connections }) {
+ const { units, manifest } = readConfigurationStore({ file, environment, appUniqueName, solutionUniqueName });
+ const ctx = {
+ spec, units, manifest, dataverse: sdk.dataverse, solutionUniqueName, validate, names: new Map(), pagesNaming: namedByPagesOf(spec),
+ inventory: connectionInventory({ connections }),
+ };
+ return {
+ environmentVariables: await restoreKind(ctx, 'environmentVariable'),
+ connectionReferences: await restoreKind(ctx, 'connectionReference'),
+ customApis: await restoreKind(ctx, 'customApi'),
+ duplicateDetectionRules: await restoreKind(ctx, 'duplicateRule'),
+ };
+}
+
+module.exports = { restoreManagedConfiguration, CONFIGURATION_RESTORE_MIN_VERSION };
diff --git a/plugins/model-apps/scripts/lib/declared-view-io.js b/plugins/model-apps/scripts/lib/declared-view-io.js
new file mode 100644
index 000000000..be81c6897
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/declared-view-io.js
@@ -0,0 +1,298 @@
+'use strict';
+// The explicit managed download's restore of declared views (views[].reconcile "declared", createIdentity "stable-v1"): each view a
+// committed view group of the build's binding store proves this app CREATED is written back into views[] as a declaration that
+// rebuilds it exactly, and every other is named. Nothing here writes, binds or publishes.
+//
+// Why a view needs more than a proof check. A view group keeps no declaration (lib/creates-stable-build.js records the row, its
+// projection baseline and its publication, not the spec it came from), so the declaration is INVERTED from the live row. An inverse
+// that guessed would be worse than none: a rebuild of a guessed declaration rewrites the view. So the inverse is accepted only when
+// - the row is the one the store bound (exact id, the table it was built on), the build created it (origin "created"), its last
+// publish settled, and it is still exactly what the build proved (projection baseline, and saved layer = published layer);
+// - the app's solution holds the row NOW: a component row of its own, or its table held with all its subcomponents (the store
+// shows it was added once, and a maker can take it out since); a membership the read cannot establish leaves it out too;
+// - the view uses only what a declaration can say: a flat AND of conditions, `in`/`not-in` groups exactly as the compiler builds
+// them, joins one level deep with their own flat filters, and nothing in the lossless fetch bag the typed tree does not show
+// (an aggregate, a quick-find filter, a nested join, a multi-<value> condition, an order the sort list does not hold); and
+// - the declaration, compiled back (view-reconcile.js compileViewIntent), equals the row part for part, and the build's own
+// planner, given the store's binding, answers noChange for it: a rebuild from the downloaded spec sends nothing for this view.
+//
+// The shape it writes: the view's current table and name, `reconcile: "declared"`, every column with its width in order, every
+// sort, every join, and `activeOnly: false` with EVERY observed condition listed, statecode eq 0 included. Writing the default
+// active filter instead would be a guess about intent the row cannot prove. Option values are written as the numbers the service
+// holds, never as labels: a number is not resolved again (sdk-build.js resolveFilterValue), so it cannot move to another option.
+// `key` is written only when the store's key is not the default `<table>/<name>` one, so the build looks the binding up under the
+// key it was made with. `viewId` pins the exact row: the download is a snapshot of this app in THIS environment (the store is too),
+// and the pin keeps a rebuild from ever following a same-named row; in another environment the pin refuses rather than guesses.
+const { normalizeGuid, projectionBaseline, canonicalJson } = require('./reconcile-common.js');
+const { readManagedFormFile } = require('./declared-form-io.js');
+const { readSavedQueryLayers } = require('./savedquery-published.js');
+const { omission, solutionMembershipCheck } = require('./managed-restore-report.js');
+const viewReconcile = require('./view-reconcile.js');
+const { compareVersions, isPluginVersion, CREATE_IDENTITY_MIN_VERSION } = require('./app-spec.js');
+
+const FAMILY = 'view';
+// A view's solution component type (Saved Query).
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/solutioncomponent
+const VIEW_COMPONENT = 26;
+const SETTLED = new Set(['confirmed', 'not-needed']);
+const lc = (v) => String(v == null ? '' : v).toLowerCase();
+const isNotFound = (err) => !!err && (err.statusCode === 404 || err.status === 404);
+// The keys of the SDK's typed view (types/view.ts) the inverse reads. A key outside these is something the typed layer shows that a
+// declaration cannot say, so the view is not inverted.
+const COLUMN_KEYS = new Set(['name', 'width', 'order', 'relatedEntity', 'sourceAttribute']);
+const CONDITION_KEYS = new Set(['attribute', 'operator', 'value', 'entityname']);
+const LINK_KEYS = new Set(['name', 'from', 'to', 'alias', 'linkType', 'filters']);
+const SORT_KEYS = new Set(['attribute', 'descending', 'entityname']);
+const onlyKeys = (o, allowed) => !!o && typeof o === 'object' && !Array.isArray(o) && Object.keys(o).every((k) => allowed.has(k) || o[k] === undefined);
+
+class Unsupported extends Error {}
+const unsupported = (why) => { throw new Unsupported(why); };
+
+// A condition value as the declaration writes it. An integer the service holds (an option value, a count) is written as a number:
+// the build resolves only a STRING as an option label (sdk-build.js resolveFilterValue, lib/view-filter-labels.js), so a number
+// compiles back to exactly this text. Anything else stays the text the service holds.
+function valueOf(text) {
+ if (typeof text !== 'string') unsupported('a condition value that is not text');
+ return /^-?\d{1,15}$/.test(text) && String(Number(text)) === text ? Number(text) : text;
+}
+
+// One typed filter ({ type: 'and', conditions, groups }) as declaration filters, or Unsupported. A condition becomes
+// { attr, op, value? , relatedEntity? }; a group becomes in/not-in only when it is exactly what compileConditions builds for one: an
+// 'or' of eq (in) or an 'and' of ne (not-in) conditions on ONE attribute of ONE scope, with no nested group. Every other tree (an
+// OR of different columns, a nested mix) is refused, never flattened. `scoped` says whether a condition may name a join.
+function filtersOf(tree, { scoped }) {
+ if (!tree || typeof tree !== 'object' || tree.type !== 'and') unsupported('a filter that is not a plain AND');
+ if (!onlyKeys(tree, new Set(['type', 'conditions', 'groups']))) unsupported('a filter with parts the typed tree does not name');
+ const out = [];
+ const scopeOf = (c) => {
+ const scope = c.entityname === undefined || c.entityname === '' ? undefined : lc(c.entityname);
+ if (scope !== undefined && !scoped) unsupported('a join filter condition on another table');
+ return scope;
+ };
+ for (const c of tree.conditions || []) {
+ if (!onlyKeys(c, CONDITION_KEYS) || typeof c.attribute !== 'string' || typeof c.operator !== 'string') unsupported('a condition the typed tree does not name');
+ if (c.operator === 'in' || c.operator === 'not-in') unsupported('a single-condition in/not-in');
+ const f = { attr: lc(c.attribute), op: c.operator };
+ if (c.value !== undefined) f.value = valueOf(c.value);
+ const scope = scopeOf(c);
+ if (scope !== undefined) f.relatedEntity = scope;
+ out.push(f);
+ }
+ for (const g of tree.groups || []) {
+ if (!g || (g.type !== 'or' && g.type !== 'and') || (g.groups || []).length || !(g.conditions || []).length) unsupported('a nested filter group');
+ const sub = g.type === 'or' ? 'eq' : 'ne';
+ const first = g.conditions[0];
+ const scope = onlyKeys(first, CONDITION_KEYS) ? scopeOf(first) : undefined;
+ for (const c of g.conditions) {
+ if (!onlyKeys(c, CONDITION_KEYS) || c.operator !== sub || lc(c.attribute) !== lc(first.attribute) || c.value === undefined || scopeOf(c) !== scope) {
+ unsupported('a filter group that is not one in/not-in list');
+ }
+ }
+ const f = { attr: lc(first.attribute), op: g.type === 'or' ? 'in' : 'not-in', values: g.conditions.map((c) => valueOf(c.value)) };
+ if (scope !== undefined) f.relatedEntity = scope;
+ out.push(f);
+ }
+ return out;
+}
+
+const bagNodes = (node) => (node && Array.isArray(node.c) ? node.c.map((k) => (k && k.node ? k.node : k)).filter((n) => n && typeof n === 'object') : []);
+const bagAttr = (node, name) => ((Array.isArray(node.a) ? node.a : []).find((p) => p[0] === name) || [])[1];
+const countIn = (node, name) => bagNodes(node).reduce((s, k) => s + countIn(k, name), 0) + (node && node.n === name ? 1 : 0);
+const typedCount = (g) => (g ? (g.conditions || []).length + (g.groups || []).reduce((s, x) => s + typedCount(x), 0) : 0);
+
+// What the lossless fetch bag holds that the typed tree does not show: the fetch is { a, c: [{ i, node: { n: 'entity', a, c } }] },
+// each node { n, a: [[name, value]], c }. A view whose query does more than its typed parts say is not inverted: the declaration
+// would rebuild a different query in a new environment, and say nothing true about this one.
+function bagIssue(view) {
+ const bag = view.fetchBag;
+ const entity = bagNodes(bag).find((n) => n.n === 'entity');
+ if (!bag || !entity) return 'no readable query';
+ if (lc(bagAttr(bag, 'aggregate')) === 'true' || lc(bagAttr(bag, 'distinct')) === 'true' || bagAttr(bag, 'top') !== undefined || bagAttr(bag, 'count') !== undefined) {
+ return 'an aggregate, distinct or limited query';
+ }
+ const kids = bagNodes(entity);
+ if (kids.some((n) => !['attribute', 'all-attributes', 'order', 'filter', 'link-entity'].includes(n.n))) return 'a query node the typed tree does not show';
+ if (kids.some((n) => n.n === 'filter' && bagAttr(n, 'isquickfindfields') === '1')) return 'a quick-find filter';
+ if (viewReconcile.hasUnrepresentableFilter(view)) return 'a filter the typed tree does not show';
+ const links = kids.filter((n) => n.n === 'link-entity');
+ const typedLinks = Array.isArray(view.linkEntities) ? view.linkEntities : [];
+ if (links.length !== typedLinks.length) return 'a join the typed tree does not show';
+ for (const link of links) {
+ const inner = bagNodes(link);
+ if (inner.some((n) => !['attribute', 'all-attributes', 'order', 'filter'].includes(n.n))) return 'a nested join or a join part the typed tree does not show';
+ const ref = lc(bagAttr(link, 'alias') || bagAttr(link, 'name'));
+ const typed = typedLinks.find((l) => lc(l.alias || l.name) === ref);
+ const filters = inner.filter((n) => n.n === 'filter');
+ if (!typed || filters.reduce((s, f) => s + countIn(f, 'condition'), 0) !== typedCount(typed.filters)) return 'a join filter the typed tree does not show';
+ if (filters.some((f) => countIn(f, 'link-entity') || countIn(f, 'value'))) return 'a join filter the typed tree does not show';
+ }
+ if (countIn(entity, 'order') !== (view.sort || []).length) return 'an order the sort list does not show';
+ return null;
+}
+
+/**
+ * The declaration that rebuilds `view` (a typed view the SDK read, types/view.ts) under the store key `key`, or { unsupported: why }.
+ * Pure: it reads only `view`. See the header for the shape and what is refused. Whether the declaration REALLY rebuilds the view is
+ * not decided here: restoreManagedViews compiles it back and asks the planner.
+ */
+function viewDeclarationFromLive(view, { key } = {}) {
+ try {
+ if (!view || typeof view !== 'object' || typeof view.entityLogicalName !== 'string' || typeof view.name !== 'string' || !view.name.trim()) unsupported('no table or name');
+ if (view.queryType !== 0) unsupported('not a public view (queryType is not 0)');
+ if (viewReconcile.hasUnboundRelatedColumn(view)) unsupported('a joined-table column read back without its join');
+ const issue = bagIssue(view);
+ if (issue) unsupported(issue);
+ const entity = lc(view.entityLogicalName);
+ const declaration = { entity, name: view.name, reconcile: 'declared' };
+ if (typeof key === 'string' && key && key !== `${entity}/${view.name}`) declaration.key = key;
+ const columns = (view.columns || []).slice();
+ if (!columns.length) unsupported('no columns');
+ if (columns.some((c) => !onlyKeys(c, COLUMN_KEYS) || typeof c.name !== 'string' || !Number.isInteger(c.width) || c.width < 0 || typeof c.order !== 'number')) {
+ unsupported('a column the declaration cannot say');
+ }
+ declaration.columns = columns.sort((a, b) => a.order - b.order).map((c) => {
+ const o = { name: lc(c.name) };
+ if (c.relatedEntity) {
+ o.relatedEntity = lc(c.relatedEntity);
+ const source = lc(c.sourceAttribute || '');
+ if (source && source !== o.name.split('.').pop()) o.sourceAttribute = source;
+ }
+ o.width = c.width;
+ return o;
+ });
+ if (typeof view.description === 'string' && view.description.trim()) declaration.description = view.description;
+ const sort = (view.sort || []).map((s) => {
+ if (!onlyKeys(s, SORT_KEYS) || typeof s.attribute !== 'string') unsupported('a sort the declaration cannot say');
+ const o = { attr: lc(s.attribute) };
+ if (s.descending) o.dir = 'desc';
+ if (s.entityname) o.relatedEntity = lc(s.entityname);
+ return o;
+ });
+ if (sort.length) declaration.sort = sort;
+ // Every observed condition, the active filter too: activeOnly false says the list below is the whole filter.
+ declaration.activeOnly = false;
+ const filters = filtersOf(view.filters || { type: 'and', conditions: [], groups: [] }, { scoped: true });
+ if (filters.length) declaration.filters = filters;
+ const links = (view.linkEntities || []).map((l) => {
+ if (!onlyKeys(l, LINK_KEYS)) unsupported('a join part the declaration cannot say');
+ const o = { name: lc(l.name), from: lc(l.from), to: lc(l.to) };
+ if (l.alias) o.alias = lc(l.alias);
+ if (l.linkType) o.linkType = l.linkType;
+ if (l.filters) {
+ const f = filtersOf(l.filters, { scoped: false });
+ if (f.length) o.filters = f;
+ }
+ return o;
+ });
+ if (links.length) declaration.linkEntities = links;
+ return { declaration };
+ } catch (e) {
+ if (e instanceof Unsupported) return { unsupported: e.message };
+ throw e;
+ }
+}
+
+// The primary name column of `table` as the build would default a view's columns to it (sdk-build.js primaryNameOf).
+function primaryNameOf(spec, table) {
+ const e = ((spec && spec.entities) || []).find((x) => x && lc(x.schemaName) === table);
+ return e && e.primaryAttribute && e.primaryAttribute.schemaName ? lc(e.primaryAttribute.schemaName) : `${table}name`;
+}
+
+// Option values are written as numbers (valueOf), and a number is never resolved again, so the compile here keeps every value as
+// it is, as the build's resolver does for a number.
+const keepValue = (_t, _a, x) => x;
+
+// createIdentity's plugin floor, keeping a higher one the spec already names (the rule of app-components.js setAppThemeFloor).
+const floorOf = (current) => (isPluginVersion(current) && compareVersions(current, CREATE_IDENTITY_MIN_VERSION) > 0 ? current : CREATE_IDENTITY_MIN_VERSION);
+
+/**
+ * The explicit managed download's restore of declared views (--include-managed --managed-manifest <file>). For each committed view
+ * group of the store file, in key order, the view is restored into `spec.views` (mutated) only when every check of the header holds
+ * and the downloaded spec still validates with it (`validate`, the download's own validator); a restored view also restores the
+ * spec's `createIdentity: "stable-v1"` (only a stable build keeps view groups, so the store itself is the proof of the regime) with
+ * its plugin floor. Every other group is answered as an omission (lib/managed-restore-report.js) with a fixed reason, never
+ * silently dropped. Answers { restored: [{ key, id }], omitted: [omission] }; a store file that cannot be used throws
+ * `managed-manifest-unusable` (readManagedFormFile).
+ */
+async function restoreManagedViews({ sdk, spec, file, environment, appUniqueName, solutionUniqueName, validate }) {
+ const { groups, pending, invalid } = readManagedFormFile({ file, environment, appUniqueName, solutionUniqueName }, FAMILY);
+ const inSolution = solutionMembershipCheck({ sdk, solutionUniqueName, componentTypes: [VIEW_COMPONENT] });
+ const restored = [];
+ const omitted = [
+ ...pending.map((p) => omission({ kind: 'view', key: p.key, code: 'pending' })),
+ ...invalid.map((p) => omission({ kind: 'view', key: p.key, code: 'invalid' })),
+ ];
+ for (const key of [...groups.keys()].sort()) {
+ const group = groups.get(key);
+ const id = normalizeGuid(group.root && group.root.id);
+ const left = (code, name) => omitted.push(omission({ kind: 'view', id, key, name, code }));
+ const record = id ? (group.records || []).find((r) => r && r.kind === FAMILY && normalizeGuid(r.id) === id) : null;
+ if (!record) { left('invalid'); continue; }
+ if (record.origin !== 'created') { left('not-created'); continue; }
+ const publication = group.publication || {};
+ if (!SETTLED.has(publication.state)) { left('publication-unsettled'); continue; }
+ let art;
+ try {
+ await sdk.fetchArtifact('view', id, { overwrite: true });
+ art = await sdk.getArtifact('view', id);
+ } catch (e) {
+ left(isNotFound(e) ? 'missing' : 'unread');
+ continue;
+ }
+ if (!art || typeof art !== 'object') { left('missing'); continue; }
+ const name = typeof art.name === 'string' ? art.name : undefined;
+ const table = lc(publication.scope && publication.scope.table);
+ if (normalizeGuid(art.id) !== id || !table || lc(art.entityLogicalName) !== table) { left('wrong-table', name); continue; }
+ // The store proves the build put the row in the solution once; the solution must still hold it now (lib/managed-restore-report.js).
+ const membership = await inSolution(id, VIEW_COMPONENT, table);
+ if (membership) { left(membership, name); continue; }
+ const live = viewReconcile.liveFull(art);
+ const observed = projectionBaseline(live).intentSha256;
+ const baseline = group.consumerState && group.consumerState.baseline;
+ if (observed !== record.intentSha256 || (baseline && baseline.intentSha256 !== observed)) { left('changed', name); continue; }
+ let layers;
+ try {
+ layers = await readSavedQueryLayers(FAMILY, sdk.dataverse, group);
+ } catch {
+ left('unread', name);
+ continue;
+ }
+ if (layers.savedSha256 !== layers.publishedSha256) { left('unpublished-changes', name); continue; }
+ if (publication.state === 'confirmed' && publication.desiredSha256 && publication.desiredSha256 !== layers.savedSha256) { left('changed', name); continue; }
+ const inverse = viewDeclarationFromLive(art, { key });
+ if (!inverse.declaration) { left('unsupported', name); continue; }
+ const declaration = { ...inverse.declaration, viewId: id };
+ if (viewReconcile.declaredViewKey(declaration) !== key) { left('key-mismatch', name); continue; }
+ const primaryName = primaryNameOf(spec, table);
+ const { errors, intent } = viewReconcile.compileViewIntent(declaration, { resolveValue: keepValue, primaryName });
+ const desired = intent && viewReconcile.desiredFull(intent, live);
+ if (errors.length || !desired || viewReconcile.PARTS.some((p) => canonicalJson(desired[p]) !== canonicalJson(live[p]))) { left('not-equivalent', name); continue; }
+ // The build's own planner, given exactly the binding the store holds: a rebuild must answer noChange, bind as it is, and send
+ // nothing. GET only (view-reconcile.js planViewReconcile).
+ let plan;
+ try {
+ plan = await viewReconcile.planViewReconcile({ view: declaration, sdk, resolveValue: keepValue, primaryName }, {
+ managed: { lookup: async (kind, k) => (kind === FAMILY && k === key ? record : null) },
+ });
+ } catch {
+ left('unread', name);
+ continue;
+ }
+ if (plan.action !== 'noChange' || !plan.bindUnchanged || plan.refused.length || plan.unknown.length || normalizeGuid(plan.viewId) !== id) { left('would-change', name); continue; }
+ const views = Array.isArray(spec.views) ? spec.views : [];
+ // A declaration is replaced by its store key, never by its name: two views of one name on one table are two groups with two
+ // keys (views[].key), and each is restored as itself.
+ const at = views.findIndex((v) => v && viewReconcile.declaredViewKey(v) === key);
+ const next = at >= 0 ? views.map((v, i) => (i === at ? declaration : v)) : [...views, declaration];
+ const candidate = { ...spec, views: next, createIdentity: 'stable-v1', minimumPluginVersion: floorOf(spec.minimumPluginVersion) };
+ const check = validate(candidate);
+ if (!check || !check.ok) { left('invalid-in-spec', name); continue; }
+ spec.views = next;
+ spec.createIdentity = candidate.createIdentity;
+ spec.minimumPluginVersion = candidate.minimumPluginVersion;
+ restored.push({ key, id });
+ }
+ return { restored, omitted };
+}
+
+module.exports = { restoreManagedViews, viewDeclarationFromLive };
diff --git a/plugins/model-apps/scripts/lib/managed-restore-report.js b/plugins/model-apps/scripts/lib/managed-restore-report.js
new file mode 100644
index 000000000..1055eff36
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/managed-restore-report.js
@@ -0,0 +1,148 @@
+'use strict';
+// The read-only seam the explicit managed download (--include-managed) shares between the families it restores from a build's
+// binding store, and the not-round-tripped report it finalizes once they have run.
+//
+// Why a seam at all: the plain download names what it leaves out (download-model-app.js notRoundTrippedSummary) before anything
+// is restored, so a family the managed download DOES restore (a proved view, a proved chart) would still be reported as left out
+// — the same false statement the report exists to prevent. The CLI asks runDownload to defer the report (`deferReport`), restores
+// what it can, subtracts the ids it restored — exact ids, never display names: two views of one table may share a name — and prints
+// the report once. A library caller that does not ask gets the report as it always did.
+//
+// What a family adapter answers is one shape, so the CLI can name every item it left out the same way:
+// { restored: [key], omitted: [{ kind, id?, key?, name?, code, reason }] }
+// `reason` is fixed text chosen by `code` (REASONS below), never a service answer, an XML fragment or an exception's text: an
+// omission is printed and written to the result, and the service's own words can carry anything (a private value, a row's content).
+//
+// The source store is read, never written, and its bytes are fingerprinted before the first family reads it and again before the
+// download publishes anything (storeRevision): a build that rewrote the store in between could have changed what the families
+// proved, and the families read it independently, so the download stops instead of writing a mix of two revisions.
+const crypto = require('node:crypto');
+const fs = require('node:fs');
+const { normalizeGuid } = require('./reconcile-common.js');
+const { createSolutionMembership } = require('./solution-membership.js');
+const { tableRefs } = require('./app-components.js');
+
+const codeError = (code, message) => Object.assign(new Error(message), { code });
+
+// Every reason an item is left out, as the text the operator reads. Fixed so an omission can never echo what a service said.
+const REASONS = Object.freeze({
+ 'pending': 'its last build did not finish proving it (an attempt is still pending in the binding store)',
+ 'invalid': 'its record in the binding store is not usable',
+ 'not-created': 'its build adopted it rather than created it, and an adopted row is not one the app authored',
+ 'publication-unsettled': 'its last publish was not confirmed, so the published layer may not be what the build saved',
+ 'unpublished-changes': 'its saved layer differs from its published layer (a change was saved and not published)',
+ 'unread': 'it could not be read from the service',
+ 'missing': 'the row the build created is no longer in the service',
+ 'wrong-table': 'the row the build created is on a different table now',
+ 'changed': 'it was changed since its last build proved it',
+ 'unsupported': 'it uses a shape the App Spec cannot declare exactly',
+ 'not-equivalent': 'the declaration rebuilt from it does not compile back to the row as it is',
+ 'key-mismatch': 'its current table and name no longer give the key its build bound it under (it was renamed)',
+ 'would-change': 'a rebuild from the declaration would change it',
+ 'invalid-in-spec': 'the declaration rebuilt from it does not validate in the downloaded spec',
+ 'ownership-unproven': 'no binding store record proves this app authored it, so it is not declared',
+ 'not-in-solution': 'the solution of the app does not hold it now (no component row of its own, and its table is not held with all its subcomponents)',
+ 'membership-unknown': 'whether the solution of the app holds it now could not be read from the service',
+ 'secret-withheld': 'it is a secret variable: its Key Vault reference is never downloaded, and a secret is not round-tripped',
+ 'parent-unproven': 'the parent variable it names is not one this download restores at exactly that row',
+ 'multiple-values': 'it has more than one current value row, and a download never picks one',
+ 'required-value-missing': 'it is required but has neither a default nor a value, so a rebuild of it would stop as incomplete; a download never fills one in',
+ 'unsupported-dependency': 'it depends on a custom connector, which a download cannot prove is the same one wherever the spec is rebuilt',
+ 'page-unready': 'a page of the app names it and it is not ready for one (no connection this download could prove is among the connections of the environment and of its connector, or no registered implementation), so declaring it would stop a rebuild before that page',
+ 'implemented': 'it has an implementation (a plug-in type) registered in this environment, which an App Spec never declares and a rebuild elsewhere would not have',
+ 'state-unproven': 'the binding store records its fields and conditions but not the publication state its build left it in, so a state changed outside the plugin cannot be told apart, and a download never states one it cannot prove',
+ 'fields-withheld': 'the named parts are never written by a download (they can hold a private or environment-specific value); a rebuild leaves them as they are in the service',
+});
+
+const SAFE_TEXT = /^[^\u0000-\u001f\u007f]{1,400}$/;
+const safeText = (v) => (typeof v === 'string' && SAFE_TEXT.test(v) ? v : undefined);
+
+/**
+ * One item left out, carrying only safe identity (a normalized GUID, the store key, the row's name) and the fixed reason of its
+ * code. `fields` names withheld parts of an item that is otherwise reported (never their values). An unknown code is a bug in the
+ * caller, so it throws rather than print a reason nobody wrote.
+ */
+function omission({ kind, id, key, name, fields, code }) {
+ if (!Object.prototype.hasOwnProperty.call(REASONS, code)) throw new Error(`unknown omission code '${code}'`);
+ const guid = id ? normalizeGuid(id) : '';
+ const out = { kind: String(kind) };
+ if (guid) out.id = guid;
+ if (safeText(key)) out.key = key;
+ if (safeText(name)) out.name = name;
+ if (Array.isArray(fields)) {
+ const named = fields.map(safeText).filter(Boolean);
+ if (named.length) out.fields = named;
+ }
+ out.code = code;
+ out.reason = REASONS[code];
+ return out;
+}
+
+/**
+ * The not-round-tripped inventory (download-model-app.js readDescriptionInventory) without the rows the managed restore put back
+ * into the spec, matched by normalized id per class: `restoredIds` is `{ views: [id], charts: [id] }`. A class left with no row loses
+ * its key, as roundTrippedAware drops an empty globalChoices: an empty list would read as "the read found none". The inventory is
+ * not changed; with nothing restored it is returned as it is, so the report stays byte for byte what the plain download prints.
+ */
+function subtractRestored(inventory, restoredIds) {
+ if (!inventory || !restoredIds) return inventory;
+ let out = inventory;
+ for (const [kind, ids] of Object.entries(restoredIds)) {
+ if (!Array.isArray(ids) || !ids.length || !Array.isArray(inventory[kind])) continue;
+ const gone = new Set(ids.map((id) => normalizeGuid(id)).filter(Boolean));
+ const left = inventory[kind].filter((row) => !(row && row.id && gone.has(normalizeGuid(row.id))));
+ if (left.length === inventory[kind].length) continue;
+ if (out === inventory) out = { ...inventory };
+ if (left.length) out[kind] = left;
+ else delete out[kind];
+ }
+ return out;
+}
+
+/**
+ * The fingerprint of the source store's bytes (sha256), or throws `managed-manifest-unusable` when it cannot be read. Compared with
+ * `assertStoreUnchanged` before anything is published.
+ */
+function storeRevision(file, { fsImpl = fs } = {}) {
+ let bytes;
+ try {
+ bytes = fsImpl.readFileSync(file);
+ } catch (e) {
+ throw codeError('managed-manifest-unusable', `the managed binding store ${file} could not be read (${(e && e.code) || 'error'})`);
+ }
+ return crypto.createHash('sha256').update(bytes).digest('hex');
+}
+
+function assertStoreUnchanged(file, revision, { fsImpl = fs } = {}) {
+ let now;
+ try {
+ now = storeRevision(file, { fsImpl });
+ } catch {
+ now = null;
+ }
+ if (now !== revision) {
+ throw codeError('managed-manifest-changed', `the managed binding store ${file} changed while this download read it (a build ran against this app?), so what it proved cannot be told apart from what it proves now. Run the download again`);
+ }
+}
+
+/**
+ * The current-membership check a restore makes before it accepts a row: the store proves the build created the row in the app's
+ * solution once, not that the solution still holds it (a maker can remove it, or turn the table into a shell). Answers a function
+ * `(componentId, componentType, table) => null | 'not-in-solution' | 'membership-unknown'`: null when the solution is proven to hold
+ * the row now, by a component row of its own or by its table held with ALL its subcomponents (`rootcomponentbehavior` 0; a table held
+ * as a shell or without subcomponents does not carry its views and charts). It reuses the build's own reader (lib/solution-membership.js)
+ * so the restore accepts exactly what a build would count as a member, reads the solution once per family restore, and sends nothing:
+ * a restore never repairs membership. A read that fails, a solution that cannot prove membership, or a table whose MetadataId cannot
+ * be resolved answers 'membership-unknown', never 'not-in-solution', and never acceptance.
+ */
+function solutionMembershipCheck({ sdk, solutionUniqueName, componentTypes }) {
+ const resolveTableId = async (logical) => (await tableRefs(sdk.dataverse, [logical])).get(String(logical).toLowerCase()).metadataId;
+ const membership = createSolutionMembership({ read: sdk, solutionUniqueName, componentTypes, resolveTableId });
+ return async (componentId, componentType, table) => {
+ const status = await membership.status(componentId, componentType, { table });
+ if (status === 'held') return null;
+ return status === 'absent' ? 'not-in-solution' : 'membership-unknown';
+ };
+}
+
+module.exports = { REASONS, omission, subtractRestored, storeRevision, assertStoreUnchanged, solutionMembershipCheck };
diff --git a/plugins/model-apps/scripts/lib/page-scroll.js b/plugins/model-apps/scripts/lib/page-scroll.js
index 83cac5ee1..e769e2191 100644
--- a/plugins/model-apps/scripts/lib/page-scroll.js
+++ b/plugins/model-apps/scripts/lib/page-scroll.js
@@ -210,13 +210,13 @@ class PageReader {
if (result.v === true) {
for (const { box, parent } of result.path) {
const at = box.node.getStart(sf);
- const fills = paddedAt.has(at) ? null : this.overhangs(box, parent);
- if (!fills) continue;
+ const over = paddedAt.has(at) ? null : this.overhangs(box, parent);
+ if (!over) continue;
paddedAt.add(at);
const where = this.place(box.node);
const name = this.elementName(box);
const fix = this.fixFor(box, 'padding');
- problems.push({ code: 'scroll-context-padding', ...where, element: name, fix, message: paddingMessage(name, where, fix, fills) });
+ problems.push({ code: 'scroll-context-padding', ...where, element: name, fix, message: paddingMessage(name, where, fix, over) });
}
continue;
}
@@ -908,7 +908,8 @@ class PageReader {
// `calc(100% - 64px)` with 16px padding on each side, leave room for the padding and are not refused; nor is a calc() whose padding is a
// token, whose overhang the check cannot prove. One sized by flex is laid out with its padding counted, and a fixed length is the size the
// author chose. A scroll container in a flex column also shrinks to fit (its automatic minimum height is 0).
- // Returns the value that fills the container ("100%", "calc(100% - 8px)"), or null.
+ // Returns the value that fills the container ("100%", "calc(100% - 8px)") and, when the other of height and maxHeight is a fixed length
+ // that caps the box, that bound (`cap`: { key, value }); or null.
overhangs(box, parent) {
const style = this.styleOf(box);
const sizing = style.get('boxSizing');
@@ -939,19 +940,26 @@ class PageReader {
};
let fills = null;
const bounds = [];
+ let fixed = null;
for (const key of ['height', 'maxHeight']) {
const v = style.get(key);
if (v === undefined || !v.known || (typeof v.value === 'string' && /^(?:auto|none)$/i.test(v.value.trim()))) continue;
const c = classOf(v);
if (c === 'fill') fills = fills || v.value.trim();
+ if (c === 'maybe' && fixedLength(v.value)) fixed = { key, value: typeof v.value === 'number' ? `${v.value}px` : v.value.trim() };
bounds.push(c);
}
if (!fills) return null;
const used = bounds.includes('room') ? 'room' : bounds.includes('maybe') ? 'maybe' : 'fill';
- if (used !== 'room') return fills;
+ // A box that fills its container and is capped by a fixed length (height "100%" under maxHeight "400px") is min(container, 400px) tall
+ // plus its padding: it overhangs only a container shorter than 400px plus that padding, and the message says so. It is still refused,
+ // as the host's height is not known here. A minHeight other than auto or 0 may hold it at the container's height, so then it is not
+ // said.
const min = style.get('minHeight');
- if (min === undefined || (min.known && (isAutoMin(min) || isZero(min).v === true))) return null;
- return min.known && classOf(min) === 'room' ? null : fills;
+ const minFree = min === undefined || (min.known && (isAutoMin(min) || isZero(min).v === true));
+ if (used !== 'room') return { fills, cap: used === 'maybe' && fixed && minFree ? fixed : null };
+ if (minFree) return null;
+ return min.known && classOf(min) === 'room' ? null : { fills, cap: null };
}
place(node) {
@@ -1057,6 +1065,8 @@ function derived(value, pair) {
function sameEffect(key, a, b) {
if (key === 'flexGrow') return Number(a) > 0 === Number(b) > 0;
+ // `overflowY: "var(--Scroll)"` and `overflow: "var(--scroll)"` read two custom properties, so they do not provably agree.
+ if (opaqueCss(String(a)) || opaqueCss(String(b))) return String(a) === String(b);
return String(a).trim().toLowerCase() === String(b).trim().toLowerCase();
}
@@ -1108,13 +1118,39 @@ function measure(value) {
return m ? { n: Number(m[1]), unit: m[2] } : null;
}
-// The same CSS text, whitespace and case aside: "calc(100% - 64px)" and "calc(100% - 64px)" are one value.
+// Is a height or maxHeight a fixed length, independent of the container's height? 400, "400px", "30rem". A percentage, a viewport unit (the
+// host's container is shorter than the viewport, so "100vh" never caps a box that fills it), a calc() or a keyword is not.
+function fixedLength(v) {
+ if (typeof v === 'number') return Number.isFinite(v) && v >= 0;
+ return /^(?:\d+\.?\d*|\.\d+)(?:px|rem|em|pt|pc|cm|mm|in|q|ex|ch)$/i.test(String(v).trim());
+}
+
+// The same CSS text, whitespace and case aside: "calc(100% - 64px)" and "CALC(100% - 64px)" are one value, as keywords, units and function
+// names are ASCII case-insensitive. Text that may name a custom property, an environment variable or an attribute is compared byte for byte instead (opaqueCss).
function sameValue(a, b) {
if (!a || !b || !a.known || !b.known) return false;
- const norm = (v) => (typeof v === 'number' ? `${v}px` : String(v).trim().toLowerCase().replace(/\s+/g, ' '));
+ if ([a.value, b.value].some((v) => typeof v === 'string' && opaqueCss(v))) return a.value === b.value;
+ const norm = (v) => (typeof v === 'number' ? `${v}px` : String(v).trim().replace(/\s+/g, ' ').toLowerCase());
return norm(a.value) === norm(b.value);
}
+// Is CSS text one the check does not normalize? A custom property name is case-sensitive (`var(--height)` and `var(--HEIGHT)` read two
+// properties that may hold different sizes), and escapes can spell any part of one — an escaped space, comma or parenthesis inside it
+// (`--x\ A`), the space that ends a hex escape (`--\41 B`), even its leading hyphens (`\2d \2d Height`, `\-\-Height`, `-\-Height` are all
+// `--Height`) — while a comment beside it is not part of it. So rather than find and decode names, any text with a var(), an env(), an attr(), a
+// backslash or a comment equals only the same text byte for byte, and any other comparison is not proven. That refuses some spellings of one value too
+// (`CALC(VAR(--h))` beside `calc(var(--h))`, `calc( var(--h) )`, `--\4A` beside `--\4a`), a refusal the remedy always clears.
+// An env() and an attr() are the same case: an env() name is a case-sensitive <custom-ident>, and one the host does not define takes the
+// fallback, so `calc(100% - env(safe-area-inset-bottom, -2000px))` and the same with `SAFE-AREA-INSET-BOTTOM` are two values (a 500px host
+// makes the first 500px and the second a 2500px minimum); an attr() name may be case-sensitive too (HTML and XML differ), so another case
+// of one is refused conservatively, not proven to be a different attribute.
+// https://www.w3.org/TR/css-syntax-3/#escaping https://www.w3.org/TR/css-variables-1/#defining-variables
+// https://www.w3.org/TR/css-env-1/ https://www.w3.org/TR/css-values-4/#identifier-value
+// https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Values/attr
+function opaqueCss(text) {
+ return /var\(|env\(|attr\(|\\|\/\*/i.test(text);
+}
+
// A `minHeight` that is not provably at most the height that bounds the box: CSS applies the minimum over the height and the maximum, so a
// root with `height: "100%"` and `minHeight: 2000` is 2000px tall in a 720px host, scrolls by 40px and keeps the rest cut off.
// unset, auto, 0 → fits
@@ -1297,12 +1333,15 @@ function unprovenMessage(element, place, result, at, fix) {
return `the check cannot prove the page scrolls: ${REASONS[result.reason] || result.reason}${where}. ${WHY} ${fixText(element, place, fix)}`;
}
-function paddingMessage(element, place, fix, fills) {
+function paddingMessage(element, place, fix, { fills, cap }) {
const add = 'boxSizing: "border-box"';
const how = fix.kind === 'class'
? `Add ${add} to the "${fix.slot}" slot of ${fix.hook} (the class of that <${element}>)`
: `Write ${add} as the last key of the inline style of that <${element}> and make style its last attribute`;
- return `the page scrolls, but its <${element}> at line ${place.line} fills its container (${fills}) and has vertical padding in the default content-box model, so it is taller than its container by that padding and the end of the page stays cut off below the visible area. ${how} (${RULE_REFERENCE}).`;
+ const effect = cap
+ ? `fills its container (${fills}) up to its ${cap.key} (${cap.value}) and has vertical padding in the default content-box model, so in a container shorter than ${cap.value} plus that padding it is taller than its container, and the end of the page may be cut off below the visible area`
+ : `fills its container (${fills}) and has vertical padding in the default content-box model, so it is taller than its container by that padding and the end of the page stays cut off below the visible area`;
+ return `the page scrolls, but its <${element}> at line ${place.line} ${effect}. ${how} (${RULE_REFERENCE}).`;
}
// ─── Small TypeScript helpers ────────────────────────────────────────────────────────────────────────────────────────────────────────────
diff --git a/plugins/model-apps/scripts/lib/safe-fs.js b/plugins/model-apps/scripts/lib/safe-fs.js
index 36999de30..34df143c0 100644
--- a/plugins/model-apps/scripts/lib/safe-fs.js
+++ b/plugins/model-apps/scripts/lib/safe-fs.js
@@ -244,6 +244,47 @@ function assertPlainFileTarget(filePath, opts) {
return resolved;
}
+// Inspect only, for a caller that must know BEFORE other work whether writeFileSafe(filePath) would be refused: it makes the same
+// refusals writeFileSafe makes before it writes (a folder that is a link, a target that is a link, a folder, a hard link or read-only),
+// and one more that writeFileSafe only meets as a failed write: a folder in which no new file can be made, so that its temporary
+// sibling cannot be created. That is found by creating, then removing, an empty sibling of the same shape: a look at the permission
+// bits cannot answer it (on Windows the folder's access list decides, and an access check for W_OK reads only the read-only attribute).
+// A probe that cannot then be removed is refused too (`probe-not-removed`), naming it.
+// Like every look beforehand, it says nothing about the moment of the write: a full disk, a lock taken later or a crash still fail
+// the write itself.
+function assertFileReplaceable(filePath, opts) {
+ if (typeof filePath !== 'string' || !filePath.trim()) unsafe('refusing to write: no path was given', 'uninspectable');
+ const fsImpl = (opts && opts.fs) || fs;
+ const resolved = path.resolve(filePath);
+ const realDir = assertSafeOutputDir(path.dirname(resolved), { fs: fsImpl });
+ const target = path.join(realDir, path.basename(resolved));
+ assertWritableTarget(target, fsImpl);
+ const probe = siblingTempName(realDir, path.basename(resolved));
+ let fd;
+ try {
+ fd = fsImpl.openSync(probe, 'wx');
+ } catch (err) {
+ const e = new Error(`refusing to write ${target}: a new file cannot be made in its folder ${realDir} (${(err && err.code) || err}), and the file is written by making a new one there`);
+ e.code = 'IO_ERROR';
+ e.reason = 'folder-not-writable';
+ throw e;
+ }
+ // The probe is empty and named for this process and call only (made by an exclusive create), so removing it touches nothing of
+ // anyone else's. A lock on it is waited out (unlinkWithRetry, on Windows); one that outlasts that wait does not let the look
+ // pass: a look that leaves a file of its own behind has not answered cleanly, and stopping here, before anything is replaced,
+ // is the one point where the file can be named and nothing else has changed.
+ try { fsImpl.closeSync(fd); } catch { /* the descriptor is gone either way; the removal below says whether the file is */ }
+ try {
+ unlinkWithRetry(fsImpl, probe);
+ } catch (err) {
+ const e = new Error(`refusing to write ${target}: ${probe}, an empty file this download made to learn whether its folder takes a new file, could not be removed (${(err && err.code) || err}); it holds nothing of the maker's and can be deleted`, { cause: err });
+ e.code = 'IO_ERROR';
+ e.reason = 'probe-not-removed';
+ throw e;
+ }
+ return target;
+}
+
function writeFileSafe(filePath, data, opts) {
if (typeof filePath !== 'string' || !filePath.trim()) unsafe('refusing to write: no path was given', 'uninspectable');
({ data, opts } = checkedForTokens(data, opts));
@@ -540,6 +581,7 @@ module.exports = {
sameFile,
assertSafeOutputDir,
assertPlainFileTarget,
+ assertFileReplaceable,
writeFileSafe,
appendFileSafe,
removeFileSafe,
diff --git a/plugins/model-apps/scripts/lib/savedquery-published.js b/plugins/model-apps/scripts/lib/savedquery-published.js
index 858080d68..ad9346dab 100644
--- a/plugins/model-apps/scripts/lib/savedquery-published.js
+++ b/plugins/model-apps/scripts/lib/savedquery-published.js
@@ -92,6 +92,17 @@ function savedQueryLayerSha256(family, layer) {
* not evidence that the layers are equal, nor that they differ.
*/
async function readSavedQueryLayers(family, client, group) {
+ const { savedSha256, publishedSha256 } = await readSavedQueryLayerRows(family, client, group);
+ return { savedSha256, publishedSha256 };
+}
+
+/**
+ * readSavedQueryLayers with the rows it hashed: { saved, published, savedSha256, publishedSha256 }, each row holding the compared
+ * fields and the description; `published` is null for a row that was never published. The managed download's chart restore
+ * (lib/declared-chart-io.js) checks the published chart's XML with the verifier through it, so the XML it checks is the very
+ * row whose hash it compared.
+ */
+async function readSavedQueryLayerRows(family, client, group) {
const t = TABLES[family];
if (!t) throw unverified(`"${family}" is not a view or chart family`);
const id = normalizeGuid(group && group.root && group.root.id);
@@ -102,10 +113,10 @@ async function readSavedQueryLayers(family, client, group) {
if (!ok(savedRes)) throw unverified(`the saved ${family} ${id} could not be read (status ${savedRes && savedRes.status})`);
const saved = rowOf(t, savedRes, id, 'saved', family);
const pubRes = await get(client, `/${t.collection}(${id})?${select}`, id, 'published', family);
- if (pubRes && pubRes.status === 404 && errorCode(pubRes.body) === NOT_FOUND) return { savedSha256: savedQueryLayerSha256(family, saved), publishedSha256: NEVER_PUBLISHED_SHA256 };
+ if (pubRes && pubRes.status === 404 && errorCode(pubRes.body) === NOT_FOUND) return { saved, published: null, savedSha256: savedQueryLayerSha256(family, saved), publishedSha256: NEVER_PUBLISHED_SHA256 };
if (!ok(pubRes)) throw unverified(`the published ${family} ${id} could not be read (status ${pubRes && pubRes.status})`);
const published = rowOf(t, pubRes, id, 'published', family);
- return { savedSha256: savedQueryLayerSha256(family, saved), publishedSha256: savedQueryLayerSha256(family, published) };
+ return { saved, published, savedSha256: savedQueryLayerSha256(family, saved), publishedSha256: savedQueryLayerSha256(family, published) };
}
-module.exports = { readSavedQueryLayers, savedQueryLayerSha256 };
+module.exports = { readSavedQueryLayers, readSavedQueryLayerRows, savedQueryLayerSha256 };
diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.js
index 39795bdeb..0abbf15c1 100644
--- a/plugins/model-apps/scripts/lib/sdk-build.js
+++ b/plugins/model-apps/scripts/lib/sdk-build.js
@@ -134,7 +134,7 @@ const { manifestResourceName, buildManifest, serializeManifest, parseManifestBas
// MEMBERSHIP authority (the app's live sitemap) + the cross-app shared-page scan. fetchSitemap is
// fail-closed & discriminated; fetchAppsForPages is the only way to prove a generative page is not
// shared, since a genpage has no appmodulecomponent row (grounded live probe).
-const { fetchSitemap, navigationProof, fetchAppsForPages } = require('./sitemap-pages.js');
+const { fetchSitemap, navigationProof, fetchAppsForPages, rescanWhileUnreadable } = require('./sitemap-pages.js');
// 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');
@@ -4949,7 +4949,20 @@ async function runSdkBuildPhases(spec, opts, owed) {
if (!describedCharts.has(logical)) describedCharts.set(logical, new Set());
describedCharts.get(logical).add(name);
};
-
+ // The declared views this run settled through the binding store and proved as they are (the planner answered noChange for a row
+ // the store binds, nothing was saved), as `<table>` -> Set of store keys. The publish phase used to ask for the table of EVERY declared view, changed or not, so a rebuild
+ // that changed nothing on a stable app still republished each such table — shipping whatever else was saved there, by anyone. A
+ // managed view owes its table a publish only through its store debt (managedTables.owedTables), which the phase pays anyway; so a
+ // table is no longer asked for on account of a view listed here. Every other reason to publish it — a form, a chart this run wrote,
+ // a deferred reconcile, a debt, a view not listed here — still asks for it. Only views; no request depends on it otherwise.
+ const unchangedManagedViews = new Map();
+ const noteUnchangedManagedView = (entityLogical, key) => {
+ const logical = String(entityLogical || '').toLowerCase();
+ if (!logical) return;
+ if (!unchangedManagedViews.has(logical)) unchangedManagedViews.set(logical, new Set());
+ unchangedManagedViews.get(logical).add(key);
+ };
+ const viewAsksForTable = (v) => !(v && v.reconcile === 'declared' && (unchangedManagedViews.get(String(v.entity).toLowerCase()) || new Set()).has(declaredViewKey(v)));
// 1. Solution (idempotent; header-less provisioning client).
if (has('solution')) await provisionSolution({ sdk, provision, runner, solution: sol });
// The solution's version (solution.version), set after the solution exists and only when it differs: an equal version is one read.
@@ -7247,6 +7260,11 @@ async function runSdkBuildPhases(spec, opts, owed) {
if (!out.managed) warnUnadopted('view', out.plan.viewId, out.plan, out.r);
const made = out.r.saved.find((s) => s.created);
if (made) noteSaved(def.entityLogicalName, `view ${def.name}`);
+ // A bound view this run proved as it is — the planner answered noChange for a row the store binds (bindUnchanged), nothing
+ // was refused, unknown or saved — gives its table no reason to be published in the publish phase (unchangedManagedViews).
+ // An unadopted look-alike (noChange without bindUnchanged) keeps asking, as before.
+ const settled = out.r || {};
+ if (out.plan && out.plan.action === 'noChange' && out.plan.bindUnchanged === true && !(settled.saved || []).length && !(settled.refused || []).length && !(settled.unknown || []).length && (settled.unchanged || []).some((u) => u && u.key === stableKey)) noteUnchangedManagedView(def.entityLogicalName, stableKey);
await commitSettledPublishes();
return made ? made.id : out.plan.viewId;
}
@@ -9694,8 +9712,16 @@ async function runSdkBuildPhases(spec, opts, owed) {
// 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 });
+ //
+ // A scan that halts takes the WHOLE scan again before it gives up on an app it could not read (`rescan`): every app afresh, three more times over 35 s
+ // (sitemap-pages.js rescanWhileUnreadable). Another build or maker changing that app leaves it unreadable for a moment, and the halt then asked a maker to fix an app
+ // that was not broken. The answer is the last complete scan, never the apps read again merged into an older one: another app read before the wait may take the
+ // page in during it, and the scan right before the first write in place is there to stop exactly that. One read now that holds the page halts as shared; one still
+ // unreadable halts as before. The report after the writes only warns, so it does not wait. `opts.sleep` is the tests' seam for the waits.
+ const scanShared = async (ids, { rescan = false } = {}) => {
+ const scan = rescan
+ ? await rescanWhileUnreadable(provision, ids, { excludeAppUnique: appUnique }, typeof opts.sleep === 'function' ? { sleep: opts.sleep } : {})
+ : 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. `detach` is the command that takes the page out of each app that holds it.
return { scan, entries: Array.from(scan.byId, ([id, apps]) => {
@@ -9709,9 +9735,9 @@ async function runSdkBuildPhases(spec, opts, owed) {
}) };
};
const sharedPagesNow = async (ids) => {
- const { scan, entries } = await scanShared(ids);
+ const { scan, entries } = await scanShared(ids, { rescan: true });
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, ...retryFrom(scan.cause, scan.error) });
- // `retry: NEVER`: an app whose sitemap cannot be read is one a maker has to fix or remove; the message names other apps, which are theirs.
+ // `retry: NEVER`: an app whose sitemap cannot be read even after the scans again is one a maker has to fix or remove; the message names other apps, which are theirs.
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, retry: RETRY.NEVER });
return entries;
};
@@ -10950,14 +10976,15 @@ async function runSdkBuildPhases(spec, opts, owed) {
await runner.run('publish', 'publish customizations', async () => {
const seen = new Set(owed.barrier.blockedTables());
// Routed tables: what the plain path asked for, and every table a committed group still owes, are published by the
- // managed publisher before the app; none of them is in the envelope below.
+ // managed publisher before the app; none of them is in the envelope below. A declared view this run proved unchanged is no reason
+ // to ask for its table (viewAsksForTable): its store debt, if it has one, is in owedTables.
let managedOut = { published: [], withheld: [] };
if (managedTables) {
const ask = [...owed.barrier.routedWanted(), ...managedTables.owedTables()];
for (const k of owed.barrier.routedTables()) {
if (seen.has(k)) continue;
seen.add(k);
- const asked = (spec.forms || []).some((f) => f.entity.toLowerCase() === k) || (spec.views || []).some((v) => v.entity.toLowerCase() === k) || chartsToPublish.has(k) || owed.tables.has(k);
+ const asked = (spec.forms || []).some((f) => f.entity.toLowerCase() === k) || (spec.views || []).some((v) => v.entity.toLowerCase() === k && viewAsksForTable(v)) || chartsToPublish.has(k) || owed.tables.has(k);
if (asked) ask.push(k);
}
managedOut = await tablePublication.managed(ask, { phase: 'publish', path: 'publish customizations', observed: 'managed-publish-phase' });
diff --git a/plugins/model-apps/scripts/lib/sitemap-pages.js b/plugins/model-apps/scripts/lib/sitemap-pages.js
index 0c52d9404..5aa967955 100644
--- a/plugins/model-apps/scripts/lib/sitemap-pages.js
+++ b/plugins/model-apps/scripts/lib/sitemap-pages.js
@@ -324,11 +324,12 @@ function currentSitemapRows(rows) {
// 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[], appIds: Map<lower-cased appUniqueName, appmoduleid> (the id of every app
-// the scan read, from the rows it lists the apps from: a command that acts on an app takes its id, and this scan keys its answers by unique name) } | { ok:false, error, cause? } (`cause`: the error of the read that failed, when it was one)
+// the scan read, from the rows it lists the apps from: a command that acts on an app takes its id, and this scan keys its answers by unique name),
+// unreadableReasons: Map<lower-cased appUniqueName, reason> (why each unreadable app could not be read: fetchSitemap's reasons, so `malformed` is stored XML that fails the structural check) } | { ok:false, error, cause? } (`cause`: the error of the read that failed, when it was one)
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(), savedOnly: new Map(), unreadable: [], appIds: new Map() };
+ if (!want.size) return { ok: true, byId: new Map(), savedOnly: new Map(), unreadable: [], appIds: new Map(), unreadableReasons: new Map() };
const self = opts.excludeAppUnique ? String(opts.excludeAppUnique).toLowerCase() : null;
let apps;
@@ -372,6 +373,13 @@ async function fetchAppsForPages(sdk, pageIds, opts) {
const byId = new Map();
const savedOnly = new Map();
const unreadable = [];
+ const unreadableReasons = new Map();
+ // An app that could not be read, and why — the first reason found for it, as an app is named once.
+ const unread = (app, reason) => {
+ if (unreadable.includes(app)) return;
+ unreadable.push(app);
+ unreadableReasons.set(String(app).toLowerCase(), reason);
+ };
// The id of each app this scan reads, by lower-cased unique name. Both lists the scan starts from carry it, so it costs no request.
const appIds = new Map();
for (const a of others) if (a.appmoduleid) appIds.set(String(a.uniquename).toLowerCase(), guidKey(a.appmoduleid));
@@ -390,7 +398,7 @@ async function fetchAppsForPages(sdk, pageIds, opts) {
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);
+ unread(a.uniquename, r.reason);
continue;
}
readable.push({ app: a.uniquename, sitemapId: r.sitemapId, ids: new Set(r.ids) });
@@ -403,13 +411,13 @@ async function fetchAppsForPages(sdk, pageIds, opts) {
// '<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);
+ for (const name of drafts.unreadable) unread(name, 'app-layer-ambiguous');
const unlinked = [];
for (const d of drafts.apps) {
appIds.set(String(d.name).toLowerCase(), d.appId);
let components;
try { components = await appComponentRows(sdk, d.layerKey, 62, { top: 1 }); } catch {
- unreadable.push(d.name);
+ unread(d.name, 'sitemap-component-query-failed');
continue;
}
if (!components.length) {
@@ -418,7 +426,7 @@ async function fetchAppsForPages(sdk, pageIds, opts) {
}
const sitemapId = guidKey(components[0].objectid);
if (!sitemapId) {
- unreadable.push(d.name);
+ unread(d.name, 'sitemap-component-not-found');
continue;
}
readable.push({ app: d.name, sitemapId, ids: new Set() });
@@ -435,7 +443,7 @@ async function fetchAppsForPages(sdk, pageIds, opts) {
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);
+ unread(d.name, 'sitemap-name-ambiguous');
continue;
}
readable.push({ app: d.name, sitemapId: [...ids][0], ids: new Set() });
@@ -444,7 +452,7 @@ async function fetchAppsForPages(sdk, pageIds, opts) {
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);
+ unread(a.app, layer.reason);
continue;
}
for (const id of layer.ids) {
@@ -455,7 +463,35 @@ async function fetchAppsForPages(sdk, pageIds, opts) {
}
}
- return { ok: true, byId, savedOnly, unreadable, appIds };
+ return { ok: true, byId, savedOnly, unreadable, appIds, unreadableReasons };
+}
+
+// The waits before each fresh scan of a scan that left an app unreadable (rescanWhileUnreadable): three more scans over 35 s. An app is unreadable for a moment while another
+// build or maker is changing it — its sitemap component not added yet, its saved layer answering with two current rows, a read the service throttled — and a build halted on
+// that, while the same build run minutes later passed. Waiting longer would turn every truly broken app into a stall of minutes before the halt it ends in anyway, so the
+// budget is modest.
+const UNREADABLE_RESCAN_WAITS_MS = Object.freeze([5000, 10000, 20000]);
+
+// fetchAppsForPages, taken again WHOLE — every app read afresh, the ones it could read included — after each wait in `waits`, while the last scan left an app unreadable that
+// a wait could change. The answer is always ONE complete scan, the last one taken: the caller decides on it exactly as on a first scan, so no app's answer is older than the
+// wait. Reading again only the apps that were unreadable and keeping the others' answers from before the wait let a write go ahead past an app that took the page in during
+// the wait, which the scan right before the first write in place exists to stop. Fail-closed throughout:
+// - an app read now that holds the page is in `byId`, so the caller halts as shared;
+// - an app still unreadable after the last wait is in `unreadable`, so the caller halts with the words it would have used;
+// - a scan that fails as a whole after a wait is waited out like an unreadable app, and the last one is answered as it came (the caller halts on it);
+// - an app whose stored sitemap is `malformed` (present XML that fails the structural check) is not waited for: only an edit of that app changes it, which is what the
+// caller's halt asks for. A scan whose every unreadable app is malformed is answered as it came. A failed read, an empty or missing sitemap, or an ambiguous layer is waited for.
+// A first scan that failed as a whole, or with nothing unreadable, is answered as it came: no wait and no request beyond it.
+async function rescanWhileUnreadable(sdk, pageIds, opts, { waits = UNREADABLE_RESCAN_WAITS_MS, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) } = {}) {
+ let scan = await fetchAppsForPages(sdk, pageIds, opts);
+ if (!scan.ok) return scan;
+ const waitable = (s) => !s.ok || s.unreadable.some((name) => (s.unreadableReasons && s.unreadableReasons.get(String(name).toLowerCase())) !== 'malformed');
+ for (const ms of waits) {
+ if (!waitable(scan)) break;
+ await sleep(ms);
+ scan = await fetchAppsForPages(sdk, pageIds, opts);
+ }
+ return scan;
}
// 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
@@ -689,4 +725,4 @@ async function sitemapLinkedByName(sdk, appUnique) {
return navigationOf(layer);
}
-module.exports = { liveNavEntries, navigationGenPageIds, appNavigationMatchesSitemap, sitemapGenPages, sitemapGenPageIds, decodeXmlEntities, fetchSitemap, navigationProof, fetchAppsForPages, XML_TAG, XML_ATTR };
+module.exports = { liveNavEntries, navigationGenPageIds, appNavigationMatchesSitemap, sitemapGenPages, sitemapGenPageIds, decodeXmlEntities, fetchSitemap, navigationProof, fetchAppsForPages, rescanWhileUnreadable, UNREADABLE_RESCAN_WAITS_MS, XML_TAG, XML_ATTR };
diff --git a/plugins/model-apps/scripts/lib/solution-membership.js b/plugins/model-apps/scripts/lib/solution-membership.js
index 764f3312d..06cc25cfe 100644
--- a/plugins/model-apps/scripts/lib/solution-membership.js
+++ b/plugins/model-apps/scripts/lib/solution-membership.js
@@ -125,17 +125,27 @@ function createSolutionMembership({ read, solutionUniqueName, componentTypes, re
}
return tableIds.get(logical);
};
+ // 'held' 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. 'unknown' when the proof could not be
+ // looked for: the solution's rows could not be read, or a table held whole might be the component's but its
+ // MetadataId could not be resolved. 'absent' otherwise: the rows were read and none of them vouches for it.
+ // The build only needs held-or-not (`has`); a reader that must not treat an outage as "not in the solution" (the
+ // managed download's restore) asks for all three.
+ async function status(componentId, componentType, { table } = {}) {
+ const held = await members();
+ if (!held) return 'unknown';
+ if (held.members.has(keyOf(componentType, componentId))) return 'held';
+ if (!table || typeof resolveTableId !== 'function' || !held.wholeTables.size) return 'absent';
+ if (!TABLE_SUBCOMPONENT_TYPES.has(Number(componentType))) return 'absent';
+ const tableId = await tableIdOf(table);
+ if (!tableId) return 'unknown';
+ return held.wholeTables.has(tableId) ? 'held' : 'absent';
+ }
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);
+ status,
+ // True only when the solution is PROVEN to hold the component (`status` is 'held').
+ async has(componentId, componentType, options) {
+ return (await status(componentId, componentType, options)) === 'held';
},
// 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.
diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.js
index e12e5d498..e33e8b239 100644
--- a/plugins/model-apps/scripts/lib/verify-spec.js
+++ b/plugins/model-apps/scripts/lib/verify-spec.js
@@ -37,6 +37,8 @@ const { verifyDeclaredDashboard } = require('./declared-dashboard-io.js');
const { verifyDeclaredRule, declaredRulesByKey } = require('./declared-rule-io.js');
const { verifyDeclaredBpf, declaredBpfsByKey } = require('./declared-bpf-io.js');
const { declaredFeatureOn } = require('./declared-features.js');
+const { isDeclaredChart, declaredChartKey } = require('./chart-reconcile.js');
+const { chartContentChecks } = require('./chart-verify.js');
const { childRelationshipsFor } = require('./app-spec.js');
const { placementOf, resolvePlacement, columnSequence, neighbourOf, tokenLabel, findGridSection, AUTO_TAB_NAME } = require('./form-subgrid-placement.js');
const { formOrderSpecOf, isDeclaredFormOn, isMainForm, selectDefaultForm, plannedMainFormSequence, displayConditionsOrder, compareServedOrder } = require('./form-order.js');
@@ -419,10 +421,67 @@ async function verifySpec(spec, read, opts = {}) {
}
}
});
- plan.each(spec.charts || [], async ({ add }, charts) => {
+ // CHARTS — presence, then content. A chart is found, then held to what the spec says it is (lib/chart-verify.js chartContentChecks):
+ // its type, the query it draws (table, group-by column, measure), and the description and title the build owns. A chart that exists
+ // with another type, grouping, measure or an added filter used to pass on its name alone.
+ //
+ // Which row is the chart: a DECLARED chart (charts[].reconcile "declared") that the managed bindings of this workspace
+ // (`opts.managedManifest`) bind is the bound row, read by its id — the build resolves it so, and a namesake made since is not it. A
+ // bound row that is gone is missing; the name is not asked in its place. A group with an attempt still pending, or a stored record
+ // that is not usable, proves nothing about the chart: it is unverified (its managed listing says why). Every other chart is found by
+ // its name on its table, as before; two charts of that name are not told apart, so the chart is present but its content unverified.
+ //
+ // The content columns are read only for the comparison; a reader that answers without them (the eval's synthesized reader answers
+ // ids) has its charts checked for presence, and their content named unverified — a row's presence never stands in for what it holds.
+ const chartGuid = (g) => String(g || '').trim().toLowerCase().replace(/^\{|\}$/g, '');
+ const chartSelect = ['savedqueryvisualizationid', 'primaryentitytypecode', 'name', 'description', 'datadescription', 'presentationdescription'];
+ const chartBinding = (ch) => {
+ const m = opts.managedManifest;
+ if (!m || !Array.isArray(m.groups) || !isDeclaredChart(ch)) return null;
+ const key = declaredChartKey(ch);
+ const unsettled = (list) => (Array.isArray(list) ? list : []).find((x) => x && ((x.family === 'chart' && x.key === key) || x.family === 'store'));
+ const open = unsettled(m.pending) || unsettled(m.invalid);
+ if (open) return { key, open: `its managed binding (${key}) is not settled (${open.code || open.reason || 'managed-binding-group-invalid'}) — unverified, not proven correct` };
+ const g = m.groups.find((x) => x && x.family === 'chart' && x.key === key);
+ if (!g) return null;
+ const id = chartGuid(g.root && g.root.id);
+ if (!id) return { key, open: `its managed binding (${key}) records no chart id — unverified, not proven correct` };
+ return { key, id };
+ };
+ plan.each(spec.charts || [], async ({ add, unverified }, 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]);
+ const entity = String(ch.entity).toLowerCase();
+ const bound = chartBinding(ch);
+ if (bound && bound.open) { unverified.push(`chart:${ch.name} (${bound.open})`); continue; }
+ let row;
+ let ambiguous = false;
+ if (bound) {
+ const rows = await read.queryRecords('savedqueryvisualization', { select: chartSelect, filter: `savedqueryvisualizationid eq ${bound.id}`, top: 1 });
+ const got = rows && rows[0];
+ // Present only when the row answered IS the bound row, on the chart's table where the row says which.
+ const sameTable = !got || got.primaryentitytypecode == null || String(got.primaryentitytypecode).toLowerCase() === entity;
+ if (!got || chartGuid(got.savedqueryvisualizationid) !== bound.id || !sameTable) {
+ add('chart', ch.name, false, `the chart its managed binding (${bound.key}) is bound to (${bound.id}) was not found${got && !sameTable ? ' on its table' : ''}; a chart of the same name is not taken in its place`);
+ continue;
+ }
+ row = got;
+ } else {
+ const rows = await read.queryRecords('savedqueryvisualization', { select: chartSelect, filter: `primaryentitytypecode eq '${entity}' and name eq '${odataLit(ch.name)}'`, top: 2 });
+ const list = Array.isArray(rows) ? rows : [];
+ // A row that says it is on another table is not this chart (a reader that did not apply the table filter).
+ const onTable = list.filter((r) => r && (r.primaryentitytypecode == null || String(r.primaryentitytypecode).toLowerCase() === entity));
+ row = onTable[0];
+ ambiguous = new Set(onTable.map((r) => chartGuid(r.savedqueryvisualizationid)).filter(Boolean)).size > 1;
+ }
+ add('chart', ch.name, row);
+ if (!row) continue;
+ if (ambiguous) {
+ unverified.push(`chart-data:${ch.name} (several charts on ${entity} have this name, so which one the spec describes is not known)`);
+ continue;
+ }
+ const content = chartContentChecks(ch, row, ch.name);
+ for (const c of content.checks) add(c.kind, c.name, c.present, c.detail);
+ unverified.push(...content.unverified);
}
});
// DASHBOARDS — existence, then that every deployed chart tile is internally consistent (#586 item 3).
diff --git a/plugins/model-apps/scripts/list-connections.js b/plugins/model-apps/scripts/list-connections.js
index a28889b24..944656c70 100644
--- a/plugins/model-apps/scripts/list-connections.js
+++ b/plugins/model-apps/scripts/list-connections.js
@@ -452,6 +452,18 @@ function failureLine(error) {
};
}
+// The environment's connections as rows (connectionRowFromSdk's shape): the SDK's read, or `pac connection list` when the SDK refuses
+// (lib/sdk-first.js), answered as sdkFirst answers ({ source, value[, fallback, warnings] }). One definition for every reader of them:
+// this script, a build's proof of a connection reference's binding (build-model-app.js) and a managed download's (download-model-app.js),
+// so a download cannot call a reference bound on connections a rebuild would not see. `env` is a validated Dataverse origin.
+async function readConnections(env) {
+ return sdkFirst(env, {
+ ...connectivity,
+ fromSdk: async (sdk) => (await sdk.listConnections()).map(connectionRowFromSdk),
+ fromPac: async (refusal) => listConnectionsWithPac(env, refusal),
+ });
+}
+
async function main() {
const argv = process.argv.slice(2);
const { positional } = parseArgs(argv);
@@ -476,11 +488,7 @@ async function main() {
// The validated origin, not the caller's text, is what every read below is made for. A URL that is not a Dataverse origin is refused
// here, before the Azure CLI or PAC is started (PAC used to run first, and the text was refused only by the query after it).
const env = requireDataverseOrigin(envUrl);
- const listed = await sdkFirst(env, {
- ...connectivity,
- fromSdk: async (sdk) => (await sdk.listConnections()).map(connectionRowFromSdk),
- fromPac: async (refusal) => listConnectionsWithPac(env, refusal),
- });
+ const listed = await readConnections(env);
const connections = listed.value;
// NB: on `connectionreference`, `connectionid` is a plain String attribute (not a Dataverse
@@ -531,6 +539,7 @@ module.exports = {
failureLine,
connectionRowFromSdk,
listConnectionsWithPac,
+ readConnections,
// The `pac connection list` parsers are exported for unit tests. They consume loosely
// structured CLI output whose shape varies across PAC builds (JSON, fixed-width table,
// whitespace table), which is exactly the code most likely to break silently on a CLI
diff --git a/plugins/model-apps/scripts/tests/download-managed-configuration.test.js b/plugins/model-apps/scripts/tests/download-managed-configuration.test.js
new file mode 100644
index 000000000..6fccd108d
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/download-managed-configuration.test.js
@@ -0,0 +1,604 @@
+'use strict';
+// The explicit managed download (download-model-app.js main, --include-managed --managed-manifest <store>) of protected configuration
+// (configurationIdentity "stable-v1"): the items are built into the strict configuration org by the real build command and the real
+// SDK bundle (helpers/configuration-command.js), downloaded through main with only its connections replaced, rebuilt from the
+// downloaded spec over the same app folder, and downloaded again. runDownload answers what the plain download of this app gives: a
+// spec with no configuration lists (a plain download never writes one).
+//
+// Privacy is proved with synthetic canaries: every current value, default, value schema and secret reference the build is given is a
+// unique marker, and every file and stream the download writes (the output folder, the download SDK's own workspace, stderr and the
+// result) is scanned for each, on a restore, a refusal and a failed read alike.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { runCommand } = require('./helpers/configuration-command.js');
+const { createConfigOrg } = require('./helpers/fake-config-org.js');
+const { createMakerSdk, createNodeWorkspaceStorage } = require('../lib/maker-sdk.js');
+const { createAzHttpClient } = require('../lib/sdk-http-client.js');
+const { main: downloadMain } = require('../download-model-app.js');
+
+const SOLUTION = 'ContosoSol';
+const APP = 'contoso_configprobe';
+const APP_ID = '00000000-0000-4000-8000-00000000c0f1';
+const SP = '/providers/Microsoft.PowerApps/apis/shared_sharepointonline';
+const SQL = '/providers/Microsoft.PowerApps/apis/shared_sql';
+const CANARY = {
+ value: 'canary-value-4c1d',
+ siteValue: 'canary-site-3a9d',
+ default: 'canary-default-8e2f',
+ jsonDefault: 'canary-jsondefault-2b70',
+ schema: 'canary-schema-5e1b',
+ vault: 'canaryvault7d',
+ need: 'canary-need-91c4',
+ connection: 'canary-conn-6f3e',
+};
+const KEY_VAULT = `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.KeyVault/vaults/${CANARY.vault}/secrets/apikey`;
+
+// What the plain download of the app answers: no configuration lists.
+const PLAIN = {
+ solution: { uniqueName: SOLUTION, displayName: 'Contoso Sol', publisherPrefix: 'contoso', version: '1.2.0.0' },
+ app: { name: 'Config Probe', uniqueName: APP },
+ schemaVersion: 2,
+ entities: [],
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Links', subAreas: [{ url: 'https://contoso.example/help', title: 'Help' }] }] }] },
+};
+const VARIABLES = [
+ { schemaName: 'contoso_ApiBase', type: 'string', name: 'API base', description: 'Base address', defaultValue: `https://${CANARY.default}.contoso.example`, isRequired: true },
+ { schemaName: 'contoso_Shape', type: 'json', defaultValue: `{"k":"${CANARY.jsonDefault}"}`, valueSchema: `{"type":"object","title":"${CANARY.schema}"}` },
+ { schemaName: 'contoso_ApiKey', type: 'secret' },
+ { schemaName: 'contoso_Site', type: 'dataSource', connectorId: SP, parameterKey: 'dataset' },
+ { schemaName: 'contoso_List', type: 'dataSource', connectorId: SP, parameterKey: 'table', parentSchemaName: 'contoso_Site' },
+];
+const SETTINGS = {
+ EnvironmentVariables: [
+ { SchemaName: 'contoso_ApiBase', Value: `https://${CANARY.value}.contoso.example` },
+ { SchemaName: 'contoso_ApiKey', Value: KEY_VAULT },
+ { SchemaName: 'contoso_Site', Value: `https://${CANARY.siteValue}.sharepoint.example/sites/a` },
+ ],
+};
+const protectedSpec = (extra) => ({ ...PLAIN, minimumPluginVersion: '2.25.0', configurationIdentity: 'stable-v1', ...extra });
+
+const walk = (dir) => (fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : [path.join(dir, e.name)])) : []);
+const snapshot = (dir) => Object.fromEntries(walk(dir).map((f) => [path.relative(dir, f), fs.readFileSync(f).toString('base64')]));
+
+// The real build command over the strict org, with deployment settings carrying the canary values. Answers the org, the app folder
+// (whose .maker-workspace holds the binding store) and the store file.
+async function built({ lists = { environmentVariables: VARIABLES }, settings = SETTINGS, intercept = {}, tables } = {}) {
+ const org = createConfigOrg({ solution: { uniqueName: SOLUTION, version: '1.0.0.0', prefix: 'contoso' }, ...(tables ? { tables } : {}), intercept: (req) => (intercept.fn ? intercept.fn(req) : undefined) });
+ const appDir = path.join(makeTempDir('dl-cfg-'), 'app');
+ const settingsFile = path.join(makeTempDir('dl-cfg-settings-'), 'settings.json');
+ fs.writeFileSync(settingsFile, JSON.stringify(settings));
+ const out = await runCommand(protectedSpec(lists), { org, appDir, argv: ['--stage', 'data', '--allow-destructive', '--deployment-settings', settingsFile] });
+ assert.ok(!out.exitCode && !out.thrown && out.payload && out.payload.ok, JSON.stringify(out.payload || out.thrown));
+ const ws = path.join(appDir, '.maker-workspace');
+ const store = path.join(ws, fs.readdirSync(ws).find((f) => f.startsWith('managed-bindings.')));
+ return { org, appDir, store };
+}
+
+// download-model-app.js main with its connections replaced: the real SDK over the org's transport, a workspace of its own, and
+// runDownload answering the plain download (PLAIN).
+async function downloadSdk(org, workspace = makeTempDir('dl-cfg-ws-')) {
+ const sdk = createMakerSdk({
+ workspaceStorage: createNodeWorkspaceStorage(workspace),
+ instanceUrl: org.origin,
+ httpClient: createAzHttpClient(org.origin, { getToken: () => 'test-token-0123456789abcdef', request: (r) => org.request(r), sleep: async () => {} }),
+ });
+ await sdk.initWorkspace();
+ return sdk;
+}
+
+async function download(org, store, { out = makeTempDir('dl-cfg-out-'), managed = true, connections } = {}) {
+ const workspace = makeTempDir('dl-cfg-ws-');
+ const sdk = await downloadSdk(org, workspace);
+ const dl = Object.create(sdk);
+ dl.queryRecords = async (table, o) => (table === 'appmodule' ? [{ uniquename: APP }] : sdk.queryRecords(table, o));
+ const said = [];
+ const emitted = [];
+ const mark = org.requests.length;
+ await downloadMain({
+ argv: ['--env', org.origin, '--app', APP_ID, '--out', out, ...(managed ? ['--include-managed', '--managed-manifest', store] : [])],
+ stderr: { write: (text) => { said.push(String(text)); return true; } },
+ exit: () => {},
+ emitResult: (ok, payload) => emitted.push({ ok, payload }),
+ preflightAuth: async () => ({ ok: true }),
+ makeDownloadSdk: async () => ({ sdk: dl, cleanup() {} }),
+ makeGenpageSdk: () => ({}),
+ runDownload: async () => ({ ok: true, spec: JSON.parse(JSON.stringify(PLAIN)), pages: [], entities: [], webResources: [], droppedSubareas: 0, droppedSubareaDetails: [], notRoundTripped: null }),
+ ...(connections ? { connections } : {}),
+ });
+ assert.equal(emitted.length, 1);
+ const specFile = path.join(out, 'app-spec.json');
+ return {
+ ...emitted[0],
+ said: said.join(''),
+ out,
+ workspace,
+ requests: org.requests.slice(mark),
+ writes: org.writes(mark),
+ specBytes: fs.existsSync(specFile) ? fs.readFileSync(specFile) : null,
+ spec: fs.existsSync(specFile) ? JSON.parse(fs.readFileSync(specFile, 'utf8')) : null,
+ };
+}
+
+// No canary in any file or stream the download wrote.
+function assertNoCanary(dl) {
+ const texts = [
+ ['stderr', dl.said],
+ ['result', JSON.stringify(dl.payload)],
+ ...[dl.out, dl.workspace].flatMap((dir) => walk(dir).map((f) => [f, fs.readFileSync(f, 'latin1')])),
+ ];
+ for (const [where, text] of texts) {
+ for (const canary of Object.values(CANARY)) assert.ok(!text.includes(canary), `${canary} written to ${where}`);
+ }
+}
+
+const configurationRows = (org) => JSON.stringify(['environmentvariabledefinitions', 'environmentvariablevalues', 'connectionreferences', 'customapis', 'customapirequestparameters', 'customapiresponseproperties', 'duplicaterules', 'duplicateruleconditions', 'solutioncomponents'].map((s) => org.rows(s)));
+// A row changed outside the plugin (the maker portal's own write): its version moves on.
+const editRow = (org, set, pick, patch) => {
+ const rows = org.sets.get(set);
+ const [id, row] = [...rows].find(([, r]) => pick(r));
+ rows.set(id, { ...row, ...patch, versionnumber: row.versionnumber + 1000 });
+ return id;
+};
+// The restore library itself, over a download SDK, for a downloaded spec main's own runDownload double cannot carry (pages).
+// `connections` is the environment's connection inventory reader (main's `connections` seam); none by default.
+const restoreDirect = async (org, store, spec, connections) => require('../lib/declared-configuration-io.js').restoreManagedConfiguration({
+ sdk: await downloadSdk(org), spec, file: store, environment: org.origin, appUniqueName: APP, solutionUniqueName: SOLUTION, validate: () => ({ ok: true }),
+ ...(connections ? { connections } : {}),
+});
+const reason = (code) => require('../lib/managed-restore-report.js').REASONS[code];
+
+test('environment variables: each proved definition is restored with its parent and labels, never a value, default, schema or secret; it rebuilds as no change and downloads again byte for byte', async () => {
+ const { org, appDir, store } = await built();
+ const storeBefore = fs.readFileSync(store);
+ const workspaceBefore = snapshot(appDir);
+ const dl = await download(org, store);
+ assert.equal(dl.ok, true, JSON.stringify(dl.payload));
+ assert.deepEqual(dl.spec.environmentVariables, [
+ { schemaName: 'contoso_ApiBase', type: 'string', name: 'API base', description: 'Base address', isRequired: true },
+ { schemaName: 'contoso_Site', type: 'dataSource', name: 'contoso_Site', isRequired: false, connectorId: SP, parameterKey: 'dataset' },
+ { schemaName: 'contoso_List', type: 'dataSource', name: 'contoso_List', isRequired: false, connectorId: SP, parameterKey: 'table', parentSchemaName: 'contoso_Site' },
+ { schemaName: 'contoso_Shape', type: 'json', name: 'contoso_Shape', isRequired: false },
+ ]);
+ assert.equal(dl.spec.configurationIdentity, 'stable-v1');
+ assert.equal(dl.spec.minimumPluginVersion, '2.25.0');
+ const report = dl.payload.managedEnvironmentVariables;
+ assert.deepEqual(report.restored, ['contoso_apibase', 'contoso_site', 'contoso_list', 'contoso_shape']);
+ assert.deepEqual(report.omitted.map((o) => [o.key, o.code, o.reason]), [['contoso_apikey', 'secret-withheld', reason('secret-withheld')]]);
+ assert.deepEqual(report.withheld.map((w) => [w.key, w.fields]), [
+ ['contoso_apibase', ['defaultValue', 'value']],
+ ['contoso_site', ['value']],
+ ['contoso_shape', ['defaultValue', 'valueSchema']],
+ ]);
+ assert.match(dl.said, /WARNING: managed environment variable contoso_apikey was not restored: it is a secret variable/);
+ assert.match(dl.said, /NOTE: managed environment variable contoso_apibase was restored without defaultValue, value: /);
+ // Read only, and only what the strict org models; the store and the build's own folder are untouched (the download wrote to --out).
+ assert.deepEqual(dl.writes, []);
+ assert.deepEqual(org.unexpected, []);
+ assert.deepEqual(fs.readFileSync(store), storeBefore);
+ assert.deepEqual(snapshot(appDir), workspaceBefore);
+ assertNoCanary(dl);
+
+ // The downloaded spec, rebuilt over the same app folder with no deployment settings, changes nothing: every value, default, parent
+ // and membership stays as it was.
+ const rows = configurationRows(org);
+ const mark = org.requests.length;
+ const rebuilt = await runCommand(dl.spec, { org, appDir });
+ assert.ok(!rebuilt.exitCode && !rebuilt.thrown && rebuilt.payload.ok, JSON.stringify(rebuilt.payload || rebuilt.thrown));
+ assert.deepEqual(org.writes(mark), []);
+ assert.deepEqual(rebuilt.payload.created.configuration.unchanged.map((u) => u.key).sort(), ['contoso_ApiBase', 'contoso_List', 'contoso_Shape', 'contoso_Site']);
+ assert.equal(configurationRows(org), rows);
+ assert.deepEqual(org.unexpected, []);
+
+ const again = await download(org, store);
+ assert.ok(again.specBytes.equals(dl.specBytes), 'a second download writes the same bytes');
+ assertNoCanary(again);
+});
+
+test('environment variables: a definition changed by hand is left out, and so is the data source naming it as parent; a second value row is never picked', async () => {
+ const { org, store } = await built();
+ editRow(org, 'environmentvariabledefinitions', (r) => r.schemaname === 'contoso_Site', { description: 'edited in the maker portal' });
+ const shape = editRow(org, 'environmentvariabledefinitions', (r) => r.schemaname === 'contoso_Shape', {});
+ // A second current value under contoso_Shape, made outside the plugin: a download never chooses between them.
+ for (const n of [1, 2]) {
+ const id = `00000000-0000-4000-8000-0000000eb${n}00`;
+ org.sets.get('environmentvariablevalues').set(id, {
+ environmentvariablevalueid: id, schemaname: 'contoso_Shape', value: `{"k":"${CANARY.value}"}`, _environmentvariabledefinitionid_value: shape, versionnumber: 9000 + n,
+ });
+ }
+ const dl = await download(org, store);
+ assert.equal(dl.ok, true, JSON.stringify(dl.payload));
+ assert.deepEqual(dl.spec.environmentVariables.map((v) => v.schemaName), ['contoso_ApiBase']);
+ assert.deepEqual(dl.payload.managedEnvironmentVariables.omitted.map((o) => [o.key, o.code]).sort(), [
+ ['contoso_apikey', 'secret-withheld'],
+ ['contoso_list', 'parent-unproven'],
+ ['contoso_shape', 'multiple-values'],
+ ['contoso_site', 'changed'],
+ ]);
+ assert.deepEqual(dl.writes, []);
+ assert.deepEqual(org.unexpected, []);
+ assertNoCanary(dl);
+});
+
+test('environment variables: a read that fails leaves every item out as unread, and a store rewritten during the download stops it with the files already in --out kept as they were', async () => {
+ const intercept = {};
+ const { org, store } = await built({ intercept });
+ intercept.fn = (req) => (req.method === 'GET' && /^\/environmentvariable/.test(req.path) ? { statusCode: 500, body: { error: { code: '0x80040216', message: `failed near ${CANARY.default}` } } } : undefined);
+ const failed = await download(org, store);
+ assert.equal(failed.ok, true, JSON.stringify(failed.payload));
+ assert.equal(failed.spec.environmentVariables, undefined);
+ assert.equal(failed.spec.configurationIdentity, undefined);
+ assert.deepEqual([...new Set(failed.payload.managedEnvironmentVariables.omitted.map((o) => o.code))], ['unread']);
+ assert.equal(failed.payload.managedEnvironmentVariables.omitted.length, 5);
+ assertNoCanary(failed);
+
+ // A build that rewrites the store while this download reads it: refused before anything is written.
+ const out = makeTempDir('dl-cfg-kept-');
+ fs.writeFileSync(path.join(out, 'app-spec.json'), '{"kept":true}\n');
+ const kept = snapshot(out);
+ let rewritten = false;
+ intercept.fn = (req) => {
+ if (!rewritten && req.method === 'GET' && /^\/environmentvariabledefinitions\(/.test(req.path)) {
+ rewritten = true;
+ fs.appendFileSync(store, '\n');
+ }
+ return undefined;
+ };
+ const refused = await download(org, store, { out });
+ assert.equal(rewritten, true);
+ assert.equal(refused.ok, false);
+ assert.deepEqual(snapshot(out), kept);
+ assert.deepEqual(refused.writes, []);
+ assertNoCanary(refused);
+});
+
+test('environment variables: a required variable whose value was cleared outside the plugin, with no default, is left out rather than declared to stop a rebuild', async () => {
+ const need = { schemaName: 'contoso_Need', type: 'string', isRequired: true };
+ const { org, appDir, store } = await built({
+ lists: { environmentVariables: [VARIABLES[0], need] },
+ settings: { EnvironmentVariables: [SETTINGS.EnvironmentVariables[0], { SchemaName: 'contoso_Need', Value: CANARY.need }] },
+ });
+ const definition = org.rows('environmentvariabledefinitions').find((r) => r.schemaname === 'contoso_Need').environmentvariabledefinitionid;
+ editRow(org, 'environmentvariablevalues', (r) => r._environmentvariabledefinitionid_value === definition, { value: null });
+ const dl = await download(org, store);
+ assert.equal(dl.ok, true, JSON.stringify(dl.payload));
+ assert.deepEqual(dl.spec.environmentVariables.map((v) => v.schemaName), ['contoso_ApiBase']);
+ assert.deepEqual(dl.payload.managedEnvironmentVariables.omitted.map((o) => [o.key, o.code, o.reason]), [['contoso_need', 'required-value-missing', reason('required-value-missing')]]);
+ assert.deepEqual(dl.writes, []);
+ assertNoCanary(dl);
+ // Why it is left out: the same declaration rebuilt over the same app folder stops as incomplete. The download's own spec rebuilds.
+ const withNeed = { ...dl.spec, environmentVariables: [...dl.spec.environmentVariables, { ...need, name: 'contoso_Need' }] };
+ const stopped = await runCommand(withNeed, { org, appDir });
+ assert.ok(stopped.exitCode || stopped.thrown || !stopped.payload.ok, 'a required variable with no value stops the rebuild');
+ assert.match(JSON.stringify(stopped.payload) + stopped.stderr, /ENVIRONMENT_VARIABLE_VALUE_MISSING/);
+ const mark = org.requests.length;
+ const rebuilt = await runCommand(dl.spec, { org, appDir });
+ assert.ok(!rebuilt.exitCode && !rebuilt.thrown && rebuilt.payload.ok, JSON.stringify(rebuilt.payload || rebuilt.thrown));
+ assert.deepEqual(org.writes(mark), []);
+});
+
+test('environment variables: a required variable whose default is removed while the download proves it is judged by what the proof read, and left out', async () => {
+ const intercept = {};
+ const need = { schemaName: 'contoso_Need', type: 'string', isRequired: true };
+ const { org, appDir, store } = await built({ lists: { environmentVariables: [need] }, settings: { EnvironmentVariables: [{ SchemaName: 'contoso_Need', Value: CANARY.need }] }, intercept });
+ // Ready by its default only: the value is cleared and a default set outside the plugin, then the default is removed between the
+ // download's first read of the definition and the proof's.
+ editRow(org, 'environmentvariablevalues', () => true, { value: null });
+ editRow(org, 'environmentvariabledefinitions', () => true, { defaultvalue: CANARY.default });
+ let reads = 0;
+ intercept.fn = (req) => {
+ if (req.method === 'GET' && /^\/environmentvariabledefinitions\(/.test(req.path) && ++reads === 2) editRow(org, 'environmentvariabledefinitions', () => true, { defaultvalue: null });
+ return undefined;
+ };
+ const dl = await download(org, store);
+ assert.ok(reads > 2, `the proof reads the definition again (${reads} reads)`);
+ assert.equal(dl.ok, true, JSON.stringify(dl.payload));
+ assert.equal(dl.spec.environmentVariables, undefined);
+ assert.deepEqual(dl.payload.managedEnvironmentVariables.omitted.map((o) => [o.key, o.code]), [['contoso_need', 'required-value-missing']]);
+ assert.deepEqual(dl.writes, []);
+ assertNoCanary(dl);
+ intercept.fn = undefined;
+ const mark = org.requests.length;
+ const rebuilt = await runCommand(dl.spec, { org, appDir });
+ assert.ok(!rebuilt.exitCode && !rebuilt.thrown && rebuilt.payload.ok, JSON.stringify(rebuilt.payload || rebuilt.thrown));
+ assert.deepEqual(org.writes(mark), []);
+});
+
+test('environment variables: a required variable whose build gave it a default and no value is restored by its default alone, with the default named as withheld', async () => {
+ const need = { schemaName: 'contoso_Need', type: 'string', isRequired: true };
+ const { org, appDir, store } = await built({ lists: { environmentVariables: [{ ...need, defaultValue: CANARY.default }] }, settings: {} });
+ const dl = await download(org, store);
+ assert.equal(dl.ok, true, JSON.stringify(dl.payload));
+ assert.deepEqual(dl.spec.environmentVariables, [{ ...need, name: 'contoso_Need' }]);
+ assert.deepEqual(dl.payload.managedEnvironmentVariables.withheld.map((w) => [w.key, w.fields]), [['contoso_need', ['defaultValue']]]);
+ assertNoCanary(dl);
+ const mark = org.requests.length;
+ const rebuilt = await runCommand(dl.spec, { org, appDir });
+ assert.ok(!rebuilt.exitCode && !rebuilt.thrown && rebuilt.payload.ok, JSON.stringify(rebuilt.payload || rebuilt.thrown));
+ assert.deepEqual(org.writes(mark), []);
+});
+
+const REFERENCES = [
+ { logicalName: 'contoso_sp', connectorId: SP, name: 'SharePoint', description: 'Lists' },
+ { logicalName: 'contoso_sql', connectorId: SQL },
+];
+
+test('connection references: each proved definition is restored with its connector and labels, never its connection; it rebuilds as no change with the connection kept, and downloads again byte for byte', async () => {
+ const { org, appDir, store } = await built({ lists: { connectionReferences: REFERENCES }, settings: {} });
+ // The maker binds a connection after the build (the portal's own write): which connection is private and per environment.
+ editRow(org, 'connectionreferences', (r) => r.connectionreferencelogicalname === 'contoso_sp', { connectionid: CANARY.connection });
+ const storeBefore = fs.readFileSync(store);
+ // No page names either reference: the restore asks for no connection, so a reader that fails changes nothing and is never called.
+ let inventoryReads = 0;
+ const dl = await download(org, store, { connections: async () => { inventoryReads += 1; throw new Error('connections unreadable'); } });
+ assert.equal(dl.ok, true, JSON.stringify(dl.payload));
+ assert.equal(inventoryReads, 0);
+ assert.deepEqual(dl.spec.connectionReferences, [
+ { logicalName: 'contoso_sp', connectorId: SP, name: 'SharePoint', description: 'Lists' },
+ { logicalName: 'contoso_sql', connectorId: SQL, name: 'contoso_sql' },
+ ]);
+ assert.equal(dl.spec.configurationIdentity, 'stable-v1');
+ assert.equal(dl.spec.minimumPluginVersion, '2.25.0');
+ assert.equal(dl.spec.environmentVariables, undefined);
+ const report = dl.payload.managedConnectionReferences;
+ assert.deepEqual(report.restored, ['contoso_sp', 'contoso_sql']);
+ assert.deepEqual(report.omitted, []);
+ assert.deepEqual(report.withheld.map((w) => [w.key, w.fields, w.code]), [['contoso_sp', ['connection'], 'fields-withheld']]);
+ assert.match(dl.said, /NOTE: managed connection reference contoso_sp was restored without connection: /);
+ assert.equal(dl.payload.managedEnvironmentVariables, undefined);
+ assert.deepEqual(dl.writes, []);
+ assert.deepEqual(org.unexpected, []);
+ assert.deepEqual(fs.readFileSync(store), storeBefore);
+ assertNoCanary(dl);
+
+ const rows = configurationRows(org);
+ const mark = org.requests.length;
+ const rebuilt = await runCommand(dl.spec, { org, appDir });
+ assert.ok(!rebuilt.exitCode && !rebuilt.thrown && rebuilt.payload.ok, JSON.stringify(rebuilt.payload || rebuilt.thrown));
+ assert.deepEqual(org.writes(mark), []);
+ assert.deepEqual(rebuilt.payload.created.configuration.unchanged.map((u) => u.key).sort(), ['contoso_sp', 'contoso_sql']);
+ assert.equal(configurationRows(org), rows);
+ assert.equal(org.rows('connectionreferences').find((r) => r.connectionreferencelogicalname === 'contoso_sp').connectionid, CANARY.connection);
+ assert.deepEqual(org.unexpected, []);
+
+ const again = await download(org, store);
+ assert.ok(again.specBytes.equals(dl.specBytes), 'a second download writes the same bytes');
+ assertNoCanary(again);
+});
+
+test('connection references: one a page names with no connection, one changed by hand and one to a custom connector are left out', async () => {
+ const custom = { logicalName: 'contoso_custom', connectorId: '/providers/Microsoft.PowerApps/apis/shared_contoso-5f1', customConnectorId: '00000000-0000-4000-8000-0000000cc001' };
+ const { org, store } = await built({ lists: { connectionReferences: [...REFERENCES, custom] }, settings: {} });
+ editRow(org, 'connectionreferences', (r) => r.connectionreferencelogicalname === 'contoso_sp', { connectionid: CANARY.connection });
+ // A page naming both: the bound one is restored (its connection is one of its connector, so a rebuild's gate passes the page), the
+ // unbound one is left out, as a plain download leaves it (undeclared, so a rebuild writes the page without that gate). The
+ // connections are read once, and only for the bound one: an unbound reference needs no inventory to be left out.
+ const page = { key: 'orders', name: 'Orders', source: { kind: 'tsx', codeFile: 'pages/orders.tsx' }, connectorBindings: [{ logicalName: 'contoso_sp' }, { logicalName: 'contoso_sql' }] };
+ const spec = { ...JSON.parse(JSON.stringify(PLAIN)), pages: [page] };
+ let inventoryReads = 0;
+ const direct = await restoreDirect(org, store, spec, async () => { inventoryReads += 1; return [{ connectionId: CANARY.connection.toUpperCase(), connectorId: 'shared_sharepointonline', displayName: 'SharePoint' }]; });
+ assert.equal(inventoryReads, 1);
+ assert.deepEqual(spec.connectionReferences.map((r) => r.logicalName), ['contoso_sp']);
+ assert.deepEqual(direct.connectionReferences.omitted.map((o) => [o.key, o.code]), [['contoso_custom', 'unsupported-dependency'], ['contoso_sql', 'page-unready']]);
+
+ editRow(org, 'connectionreferences', (r) => r.connectionreferencelogicalname === 'contoso_sql', { description: 'edited in the maker portal' });
+ const dl = await download(org, store);
+ assert.equal(dl.ok, true, JSON.stringify(dl.payload));
+ assert.deepEqual(dl.spec.connectionReferences.map((r) => r.logicalName), ['contoso_sp']);
+ assert.deepEqual(dl.payload.managedConnectionReferences.omitted.map((o) => [o.key, o.code, o.reason]), [
+ ['contoso_custom', 'unsupported-dependency', reason('unsupported-dependency')],
+ ['contoso_sql', 'changed', reason('changed')],
+ ]);
+ assert.match(dl.said, /WARNING: managed connection reference contoso_sql was not restored: .*It is left out of connectionReferences\[\]/);
+ assert.deepEqual(dl.writes, []);
+ assert.deepEqual(org.unexpected, []);
+ assertNoCanary(dl);
+});
+
+test('connection references: one a page names whose connection the connections cannot prove usable is left out, whether they are unreadable, lack it, or hold it under another connector', async () => {
+ const { org, store } = await built({ lists: { connectionReferences: [REFERENCES[0]] }, settings: {} });
+ editRow(org, 'connectionreferences', () => true, { connectionid: CANARY.connection });
+ const page = { key: 'orders', name: 'Orders', source: { kind: 'tsx', codeFile: 'pages/orders.tsx' }, connectorBindings: [{ logicalName: 'contoso_sp' }] };
+ // Each is what the build's page gate (configuration-artifacts.js observe) would stop a rebuild on: no proof of the binding.
+ const cases = [
+ ['no reader', undefined],
+ ['unreadable', async () => { throw new Error('connections unreadable'); }],
+ ['not a list', async () => null],
+ ['without the connection', async () => [{ connectionId: 'contoso-other-connection', connectorId: SP, displayName: 'SharePoint' }]],
+ ['of another connector', async () => [{ connectionId: CANARY.connection, connectorId: SQL, displayName: 'SQL' }]],
+ ['connector not stated', async () => [{ connectionId: CANARY.connection, displayName: 'SharePoint' }]],
+ ];
+ const mark = org.requests.length;
+ for (const [label, connections] of cases) {
+ const spec = { ...JSON.parse(JSON.stringify(PLAIN)), pages: [page] };
+ const direct = await restoreDirect(org, store, spec, connections);
+ assert.equal(spec.connectionReferences, undefined, label);
+ assert.deepEqual(direct.connectionReferences.restored, [], label);
+ assert.deepEqual(direct.connectionReferences.omitted.map((o) => [o.key, o.code, o.reason]), [['contoso_sp', 'page-unready', reason('page-unready')]], label);
+ assert.deepEqual(direct.connectionReferences.withheld, [], label);
+ assert.ok(!JSON.stringify(direct).includes(CANARY.connection), label);
+ }
+ assert.deepEqual(org.writes(mark), []);
+ assert.deepEqual(org.unexpected, []);
+});
+
+test('connection references: one a page names whose connection is removed while the download proves it is judged by what the proof read, and left out', async () => {
+ const intercept = {};
+ const { org, store } = await built({ lists: { connectionReferences: [REFERENCES[1]] }, settings: {}, intercept });
+ editRow(org, 'connectionreferences', () => true, { connectionid: CANARY.connection });
+ let reads = 0;
+ intercept.fn = (req) => {
+ if (req.method === 'GET' && /^\/connectionreferences\(/.test(req.path) && ++reads === 2) editRow(org, 'connectionreferences', () => true, { connectionid: null });
+ return undefined;
+ };
+ const page = { key: 'orders', name: 'Orders', source: { kind: 'tsx', codeFile: 'pages/orders.tsx' }, connectorBindings: [{ logicalName: 'contoso_sql' }] };
+ const spec = { ...JSON.parse(JSON.stringify(PLAIN)), pages: [page] };
+ const direct = await restoreDirect(org, store, spec);
+ assert.ok(reads > 2, `the proof reads the reference again (${reads} reads)`);
+ assert.equal(spec.connectionReferences, undefined);
+ assert.deepEqual(direct.connectionReferences.omitted.map((o) => [o.key, o.code]), [['contoso_sql', 'page-unready']]);
+ assert.deepEqual(direct.connectionReferences.withheld, []);
+ // Why: the rebuild's page gate (configuration-build.js beforePages) passes the spec as downloaded, and stops it with the reference
+ // declared, now that it has no connection.
+ const { createConfigurationRuntime } = require('../lib/configuration-build.js');
+ const sdk = await downloadSdk(org);
+ const gate = (s) => createConfigurationRuntime({ spec: s, sdk, appUniqueName: APP }).beforePages(s.pages);
+ await gate(spec);
+ intercept.fn = undefined;
+ await assert.rejects(gate({ ...spec, configurationIdentity: 'stable-v1', minimumPluginVersion: '2.25.0', connectionReferences: [{ logicalName: 'contoso_sql', connectorId: SQL }] }), /CONNECTION_REFERENCE_UNBOUND/);
+});
+
+// A request parameter and a response property may share a unique name: they are two children, in two slots.
+const CALC = {
+ uniqueName: 'contoso_Calc', displayName: 'Calc', description: 'Adds', binding: 'global', isFunction: true,
+ requestParameters: [{ uniqueName: 'A', type: 'integer' }, { uniqueName: 'Note', type: 'string', isOptional: true, description: 'Free text' }],
+ responseProperties: [{ uniqueName: 'A', type: 'integer' }, { uniqueName: 'Ok', type: 'boolean' }],
+};
+const scaffold = (uniqueName) => ({ uniqueName, binding: 'global', requestParameters: [{ uniqueName: 'In', type: 'string' }], responseProperties: [{ uniqueName: 'Out', type: 'string' }] });
+const apiId = (org, uniqueName) => org.rows('customapis').find((r) => r.uniquename === uniqueName).customapiid;
+
+test('Custom APIs: each proved scaffold is restored with both complete child lists and its labels, never an implementation; it rebuilds as no change and downloads again byte for byte', async () => {
+ const { org, appDir, store } = await built({ lists: { customApis: [CALC, scaffold('contoso_Ping')] }, settings: {} });
+ const storeBefore = fs.readFileSync(store);
+ const dl = await download(org, store);
+ assert.equal(dl.ok, true, JSON.stringify(dl.payload));
+ // The labels the build pinned when the App Spec left them out are the row's own, so they come back as stated.
+ assert.deepEqual(dl.spec.customApis, [
+ {
+ uniqueName: 'contoso_Calc', name: 'contoso_Calc', displayName: 'Calc', description: 'Adds', binding: 'global', isFunction: true, isPrivate: false, allowedProcessingSteps: 'none', enabledForWorkflow: false,
+ requestParameters: [
+ { uniqueName: 'A', type: 'integer', name: 'contoso_Calc.A', displayName: 'A', description: 'A', isOptional: false },
+ { uniqueName: 'Note', type: 'string', name: 'contoso_Calc.Note', displayName: 'Note', description: 'Free text', isOptional: true },
+ ],
+ responseProperties: [
+ { uniqueName: 'A', type: 'integer', name: 'contoso_Calc.A', displayName: 'A', description: 'A' },
+ { uniqueName: 'Ok', type: 'boolean', name: 'contoso_Calc.Ok', displayName: 'Ok', description: 'Ok' },
+ ],
+ },
+ {
+ uniqueName: 'contoso_Ping', name: 'contoso_Ping', displayName: 'contoso_Ping', description: 'contoso_Ping', binding: 'global', isFunction: false, isPrivate: false, allowedProcessingSteps: 'none', enabledForWorkflow: false,
+ requestParameters: [{ uniqueName: 'In', type: 'string', name: 'contoso_Ping.In', displayName: 'In', description: 'In', isOptional: false }],
+ responseProperties: [{ uniqueName: 'Out', type: 'string', name: 'contoso_Ping.Out', displayName: 'Out', description: 'Out' }],
+ },
+ ]);
+ assert.equal(dl.spec.configurationIdentity, 'stable-v1');
+ assert.equal(dl.spec.minimumPluginVersion, '2.25.0');
+ assert.deepEqual(dl.payload.managedCustomApis, { restored: ['contoso_calc', 'contoso_ping'], omitted: [] });
+ assert.deepEqual(dl.writes, []);
+ assert.deepEqual(org.unexpected, []);
+ assert.deepEqual(fs.readFileSync(store), storeBefore);
+ assertNoCanary(dl);
+
+ const rows = configurationRows(org);
+ const mark = org.requests.length;
+ const rebuilt = await runCommand(dl.spec, { org, appDir });
+ assert.ok(!rebuilt.exitCode && !rebuilt.thrown && rebuilt.payload.ok, JSON.stringify(rebuilt.payload || rebuilt.thrown));
+ assert.deepEqual(org.writes(mark), []);
+ assert.deepEqual(rebuilt.payload.created.configuration.unchanged.map((u) => u.key).sort(), ['contoso_Calc', 'contoso_Ping']);
+ assert.equal(configurationRows(org), rows);
+ assert.deepEqual(org.unexpected, []);
+
+ const again = await download(org, store);
+ assert.ok(again.specBytes.equals(dl.specBytes), 'a second download writes the same bytes');
+});
+
+test('Custom APIs: an implemented one, one a page calls, and one with a child renamed, added or deleted outside the plugin are left out whole; other-language labels are named as withheld', async () => {
+ const intercept = {};
+ const names = ['contoso_Ok', 'contoso_Impl', 'contoso_Paged', 'contoso_Renamed', 'contoso_Extra', 'contoso_Gone'];
+ const { org, store } = await built({ lists: { customApis: names.map(scaffold) }, settings: {}, intercept });
+ // A plug-in type registered on the row after the build: this environment's code, which a spec never carries.
+ editRow(org, 'customapis', (r) => r.uniquename === 'contoso_Impl', { _plugintypeid_value: '00000000-0000-4000-8000-0000000ad001' });
+ editRow(org, 'customapirequestparameters', (r) => r._customapiid_value === apiId(org, 'contoso_Renamed'), { uniquename: 'Input' });
+ const extra = '00000000-0000-4000-8000-0000000ad002';
+ org.sets.get('customapiresponseproperties').set(extra, { customapiresponsepropertyid: extra, uniquename: 'More', name: 'More', displayname: 'More', description: 'More', type: 10, logicalentityname: null, _customapiid_value: apiId(org, 'contoso_Extra'), versionnumber: 9100 });
+ const props = org.sets.get('customapiresponseproperties');
+ props.delete([...props].find(([, r]) => r._customapiid_value === apiId(org, 'contoso_Gone'))[0]);
+ // An environment with two languages: the labels of the other one are not read, so never written.
+ intercept.fn = (req) => (req.method === 'GET' && /RetrieveProvisionedLanguages/.test(req.path) ? { statusCode: 200, body: { RetrieveProvisionedLanguages: [1033, 1036] } } : undefined);
+
+ const page = { key: 'calc', name: 'Calc', source: { kind: 'tsx', codeFile: 'pages/calc.tsx' }, actionBindings: [{ name: 'contoso_Paged' }] };
+ const spec = { ...JSON.parse(JSON.stringify(PLAIN)), pages: [page] };
+ const direct = await restoreDirect(org, store, spec);
+ assert.deepEqual(spec.customApis.map((a) => a.uniqueName), ['contoso_Ok']);
+ assert.deepEqual(direct.customApis.omitted.map((o) => [o.key, o.code]), [
+ ['contoso_extra', 'changed'], ['contoso_gone', 'missing'], ['contoso_impl', 'implemented'], ['contoso_paged', 'page-unready'], ['contoso_renamed', 'changed'],
+ ]);
+
+ const dl = await download(org, store);
+ assert.equal(dl.ok, true, JSON.stringify(dl.payload));
+ assert.deepEqual(dl.spec.customApis.map((a) => a.uniqueName), ['contoso_Ok', 'contoso_Paged']);
+ const report = dl.payload.managedCustomApis;
+ assert.deepEqual(report.restored, ['contoso_ok', 'contoso_paged']);
+ assert.deepEqual(report.omitted.map((o) => [o.key, o.code, o.reason]), [
+ ['contoso_extra', 'changed', reason('changed')],
+ ['contoso_gone', 'missing', reason('missing')],
+ ['contoso_impl', 'implemented', reason('implemented')],
+ ['contoso_renamed', 'changed', reason('changed')],
+ ]);
+ assert.deepEqual(report.withheld.map((w) => [w.key, w.fields]), [['contoso_ok', ['otherLanguageLabels']], ['contoso_paged', ['otherLanguageLabels']]]);
+ assert.match(dl.said, /WARNING: managed Custom API contoso_impl was not restored: it has an implementation .*It is left out of customApis\[\]/);
+ assert.equal(dl.requests.filter((r) => /RetrieveProvisionedLanguages/.test(r.path)).length, 1);
+ assert.deepEqual(dl.writes, []);
+ assert.deepEqual(org.unexpected, []);
+});
+
+const CONTACT = [{ logicalName: 'contact', attributes: ['emailaddress1', 'lastname', 'firstname', 'telephone1'] }];
+const condition = (key, column, extra) => ({ key, column, match: 'exact', ...extra });
+const ruleAt = (org, name) => [...org.sets.get('duplicaterules')].find(([, r]) => r.name === name);
+
+test('duplicate rules: none is restored, whatever state it is in, because the binding store cannot prove the state its build left it in; the download reads no rule, and the rules stay as they are', async () => {
+ const rules = [
+ { key: 'email', name: 'Same email', entity: 'contact', description: 'By mail', conditions: [condition('e', 'emailaddress1'), condition('n', 'lastname', { match: 'firstCharacters', characters: 3, ignoreBlankValues: true })] },
+ { key: 'draft', name: 'Draft rule', entity: 'contact', status: 'unpublished', conditions: [condition('l', 'lastname')] },
+ { key: 'hand', name: 'By hand', entity: 'contact', conditions: [condition('t', 'telephone1')] },
+ ];
+ const { org, appDir, store } = await built({ lists: { duplicateDetectionRules: rules }, settings: {}, tables: CONTACT });
+ // Published by its build, then unpublished outside the plugin: only its state differs from what the build left, and the store keeps
+ // no state to compare it with.
+ editRow(org, 'duplicaterules', (r) => r.name === 'By hand', { statecode: 0, statuscode: 0 });
+ const [handId] = ruleAt(org, 'By hand');
+ const storeBefore = fs.readFileSync(store);
+ const rows = configurationRows(org);
+
+ const dl = await download(org, store);
+ assert.equal(dl.ok, true, JSON.stringify(dl.payload));
+ assert.equal(dl.spec.duplicateDetectionRules, undefined);
+ assert.equal(dl.spec.configurationIdentity, undefined, 'withheld rules alone never opt the spec into protected configuration');
+ assert.equal(dl.spec.minimumPluginVersion, undefined);
+ const report = dl.payload.managedDuplicateDetectionRules;
+ assert.deepEqual(report.restored, []);
+ assert.deepEqual(report.omitted.map((o) => [o.key, o.code, o.reason]), [
+ ['draft', 'state-unproven', reason('state-unproven')],
+ ['email', 'state-unproven', reason('state-unproven')],
+ ['hand', 'state-unproven', reason('state-unproven')],
+ ]);
+ assert.equal(report.omitted.find((o) => o.key === 'hand').id, handId);
+ assert.match(dl.said, /WARNING: managed duplicate rule hand was not restored: the binding store records .*It is left out of duplicateDetectionRules\[\]/);
+ assert.deepEqual(dl.requests.filter((r) => /duplicaterule/i.test(r.path)), []);
+ assert.deepEqual(dl.writes, []);
+ assert.deepEqual(org.unexpected, []);
+ assert.deepEqual(fs.readFileSync(store), storeBefore);
+
+ // The downloaded spec declares no rule, so its rebuild leaves every rule, and the one unpublished by hand, as it is.
+ const mark = org.requests.length;
+ const rebuilt = await runCommand(dl.spec, { org, appDir });
+ assert.ok(!rebuilt.exitCode && !rebuilt.thrown && rebuilt.payload.ok, JSON.stringify(rebuilt.payload || rebuilt.thrown));
+ assert.deepEqual(org.writes(mark), []);
+ assert.equal(configurationRows(org), rows);
+ assert.deepEqual(org.unexpected, []);
+
+ const again = await download(org, store);
+ assert.ok(again.specBytes.equals(dl.specBytes), 'a second download writes the same bytes');
+});
+
+test('a download without --include-managed reads no configuration and writes none, and its result names no configuration list', async () => {
+ const { org, store } = await built();
+ const dl = await download(org, store, { managed: false });
+ assert.equal(dl.ok, true, JSON.stringify(dl.payload));
+ assert.deepEqual(dl.spec, PLAIN);
+ assert.deepEqual(Object.keys(dl.payload).filter((k) => /^managed/.test(k)), []);
+ assert.deepEqual(dl.requests.filter((r) => /environmentvariable|connectionreference|customapi|duplicaterule/i.test(r.path)), []);
+ assertNoCanary(dl);
+});
diff --git a/plugins/model-apps/scripts/tests/download-managed-lifecycle.test.js b/plugins/model-apps/scripts/tests/download-managed-lifecycle.test.js
new file mode 100644
index 000000000..d183b2fa1
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/download-managed-lifecycle.test.js
@@ -0,0 +1,360 @@
+'use strict';
+// The managed download's restore of declared views and charts, and of protected configuration, end to end, on the strict lifecycle org (helpers/fake-lifecycle-org.js,
+// which answers 501 to anything it does not model): a stable build, the CLI's own download main with --include-managed, a complete
+// rebuild of what it wrote (every phase, publish and verify included), and a second download. A restored view or chart must cost a
+// rebuild nothing a download without them does not cost: the comparison is with the plain download's spec, rebuilt the same way.
+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 { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');
+const { createLifecycleHarness, appUniqueName, publishesOf } = require('./helpers/lifecycle-harness.js');
+const { main } = require('../download-model-app.js');
+const { PREFIX } = require('../lib/managed-bindings.js');
+const { readDeploymentBindings } = require('../lib/configuration-artifacts.js');
+const { validateAppSpec } = require('../lib/app-spec.js');
+
+const roots = [];
+test.after(() => { for (const d of roots) fs.rmSync(d, { recursive: true, force: true }); });
+
+function stableSpec() {
+ return {
+ schemaVersion: 2, minimumPluginVersion: '2.21.0', createIdentity: 'stable-v1',
+ solution: { uniqueName: 'ContosoReview', displayName: 'Review', publisherPrefix: 'contoso' },
+ app: { name: 'Review', uniqueName: 'contoso_review' },
+ entities: [{
+ schemaName: 'contoso_item', displayName: 'Item', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' },
+ columns: [{ schemaName: 'contoso_kind', displayName: 'Kind', type: 'Choice', options: ['A', 'B'] }],
+ }],
+ views: [{ entity: 'contoso_item', name: 'Items', reconcile: 'declared', activeOnly: false, columns: ['contoso_name', 'contoso_kind'] }],
+ charts: [{ entity: 'contoso_item', name: 'By Kind', chartType: 'Pie', groupBy: 'contoso_kind', reconcile: 'declared' }],
+ appShell: { areas: [{ label: 'Work', groups: [{ label: 'Records', subAreas: [{ entity: 'contoso_item', title: 'Items' }] }] }] },
+ };
+}
+
+// A built app and the CLI's download main over the same org. `gated`: the build's client goes through its publication barrier, as the
+// CLI's does — a stable build refuses to create without it.
+async function builtLifecycle(spec, orgOptions = {}, buildOptions = {}) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-managed-life-'));
+ roots.push(root);
+ const org = createLifecycleOrg(orgOptions);
+ const harness = createLifecycleHarness(org, root);
+ const built = await harness.measure(() => harness.build(spec, { gated: true, ...buildOptions }));
+ assert.equal(built.error, undefined, built.error && `${built.error.stack}\nunexpected: ${JSON.stringify(org.unexpected)}`);
+ assert.equal(built.value.result.ok, true, JSON.stringify(built.value.result.steps || built.value.result));
+ const store = path.join(harness.workspaceDir, fs.readdirSync(harness.workspaceDir).find((f) => f.startsWith(PREFIX)));
+ let n = 0;
+ // `connections`: the environment's connections the download may prove a page's reference bound against (main's `connections` seam,
+ // rows as list-connections.js answers them). Read at call time, so a test can change them between downloads.
+ async function download({ managed, connections }) {
+ const out = path.join(root, `download-${n += 1}`);
+ let emitted = null;
+ const said = [];
+ // Some notes go to the process's own streams, not to the injected one: both are captured for the run, so a test can read
+ // everything the download printed.
+ const streams = [process.stdout, process.stderr].map((s) => ({ s, write: s.write }));
+ for (const x of streams) x.s.write = (t) => { said.push(String(t)); return true; };
+ try {
+ await main({
+ argv: ['--env', org.origin, '--app', appUniqueName(spec), '--out', out, ...(managed ? ['--include-managed', '--managed-manifest', store] : [])],
+ stderr: { write: (t) => { said.push(String(t)); return true; } }, exit: () => {}, emitResult: (ok, payload) => { emitted = { ok, payload }; },
+ preflightAuth: async () => ({ ok: true }), httpClient: harness.client,
+ ...(connections ? { connections: async () => connections.map((c) => ({ ...c })) } : {}),
+ });
+ } finally {
+ for (const x of streams) x.s.write = x.write;
+ }
+ assert.equal(emitted && emitted.ok, true, JSON.stringify(emitted) + said.join(''));
+ const text = fs.readFileSync(path.join(out, 'app-spec.json'), 'utf8');
+ return { out, text, spec: JSON.parse(text), payload: emitted.payload, said: said.join('') };
+ }
+ async function rebuild(downloaded, options = {}) {
+ const step = await harness.measure(() => harness.build(downloaded.spec, { appFolder: downloaded.out, gated: true, ...options }));
+ assert.equal(step.error, undefined, step.error && step.error.stack);
+ assert.equal(step.value.result.ok, true, JSON.stringify(step.value.result.steps || step.value.result));
+ return step;
+ }
+ return { org, harness, store, built, download, rebuild };
+}
+
+const familyWrites = (org, step) => org.requests.slice(step.mark, step.end)
+ .flatMap((r) => (r.operations ? r.operations : [r]))
+ .filter((r) => r.method !== 'GET' && /savedquer|AddSolutionComponent|solutioncomponent|_association/i.test(r.path));
+
+test('a complete rebuild of a managed download that restored a view and a chart sends what a rebuild of the plain download sends, and nothing to either', async () => {
+ const app = await builtLifecycle(stableSpec());
+ const managed = await app.download({ managed: true });
+ assert.deepEqual(managed.payload.managedViews, { restored: ['contoso_item/Items'], omitted: [] });
+ assert.deepEqual(managed.payload.managedCharts, { restored: ['contoso_item/By Kind'], omitted: [] });
+ assert.equal(managed.spec.views.length, 1);
+ assert.equal(managed.spec.charts.length, 1);
+
+ const restoredRebuild = await app.rebuild(managed);
+ assert.deepEqual(familyWrites(app.org, restoredRebuild), [], 'no write to a view, a chart or a solution membership');
+ const plain = await app.download({ managed: false });
+ assert.deepEqual(plain.spec.views || [], []);
+ const plainRebuild = await app.rebuild(plain);
+ // The same publishes, in the same order, and the same writes: the restored view and chart add none — no publish of their table
+ // above the ones the rest of the app's rebuild sends anyway (its forms, the app).
+ assert.deepEqual(publishesOf(app.org, restoredRebuild), publishesOf(app.org, plainRebuild));
+ assert.deepEqual(restoredRebuild.writes, plainRebuild.writes);
+
+ const again = await app.download({ managed: true });
+ assert.equal(again.text, managed.text, 'a second managed download writes the same spec, byte for byte');
+ assert.deepEqual(app.org.unexpected, []);
+});
+
+// Column security a download cannot prove is the app's own: a custom profile in the app's solution, and System Administrator, each
+// with a permission on the app's secured column and given to a user and a team. Both downloads name the custom profile and leave it
+// out of the spec; nothing in the download, the complete rebuild of what it wrote, or a second download writes to a profile, a
+// permission or a profile's links, and nothing it writes or prints names who holds a profile or which permission it is.
+test('a profile on a secured column is named and left out by a managed download, and its rebuild and a second download leave every profile, permission and holder as they were', async () => {
+ const spec = stableSpec();
+ spec.entities[0].columns.push({ schemaName: 'contoso_salary', displayName: 'Salary', type: 'Text', isSecured: true });
+ const app = await builtLifecycle(spec, { fieldSecurity: true });
+ const { org } = app;
+ const CANARY = {
+ user: '7a1c0e55-0000-4000-8000-00000000c0a1', userName: 'Canary Holder Person', team: '7a1c0e55-0000-4000-8000-00000000c0a2',
+ customPermission: '7a1c0e55-0000-4000-8000-00000000c0a3', adminPermission: '7a1c0e55-0000-4000-8000-00000000c0a4',
+ };
+ const custom = '7a1c0e55-0000-4000-8000-00000000c0a5';
+ const admin = '572329c1-a042-4e22-be47-367c6374ea45';
+ org.seedRow('systemusers', { systemuserid: CANARY.user, fullname: CANARY.userName, domainname: '[email protected]', _businessunitid_value: org.IDS.businessUnit });
+ org.seedRow('fieldsecurityprofiles', { fieldsecurityprofileid: custom, name: 'Contoso Reviewers', ismanaged: false });
+ org.seedRow('fieldsecurityprofiles', { fieldsecurityprofileid: admin, name: 'System Administrator', ismanaged: true });
+ org.seedComponent('ContosoReview', { objectid: custom, componenttype: 70 });
+ for (const [id, profile] of [[CANARY.customPermission, custom], [CANARY.adminPermission, admin]]) {
+ org.seedRow('fieldpermissions', { fieldpermissionid: id, _fieldsecurityprofileid_value: profile, entityname: 'contoso_item', attributelogicalname: 'contoso_salary', canread: 4, cancreate: 0, canupdate: 0 });
+ }
+ for (const profile of [custom, admin]) {
+ org.associations.push({ set: 'fieldsecurityprofiles', id: profile, nav: 'systemuserprofiles_association', toSet: 'systemusers', toId: CANARY.user });
+ org.associations.push({ set: 'fieldsecurityprofiles', id: profile, nav: 'teamprofiles_association', toSet: 'teams', toId: CANARY.team });
+ }
+ const columnSecurity = () => JSON.stringify({
+ profiles: [...org.rowsOf('fieldsecurityprofiles').values()].map((r) => r.data),
+ permissions: [...org.rowsOf('fieldpermissions').values()].map((r) => r.data),
+ holders: org.associations.filter((a) => a.set === 'fieldsecurityprofiles'),
+ components: org.solutionComponents().filter((c) => c.componenttype === 70),
+ });
+ const before = columnSecurity();
+ const start = org.mark();
+
+ const managed = await app.download({ managed: true });
+ assert.deepEqual(((managed.payload.fieldSecurityProfiles || {}).omitted || []).map((o) => [o.kind, o.id, o.name, o.code]), [['fieldSecurityProfile', custom, 'Contoso Reviewers', 'ownership-unproven']]);
+ assert.match(managed.said, /NOTE: 1 field security profile \(Contoso Reviewers\) is not declared in fieldSecurityProfiles\[\]/);
+ assert.equal(managed.spec.fieldSecurityProfiles, undefined);
+ assert.equal(managed.spec.entities[0].columns.find((c) => c.schemaName === 'contoso_salary').isSecured, true);
+
+ await app.rebuild(managed);
+ const again = await app.download({ managed: true });
+ assert.equal(again.text, managed.text, 'a second managed download writes the same spec, byte for byte');
+ assert.deepEqual(again.payload.fieldSecurityProfiles, managed.payload.fieldSecurityProfiles);
+
+ const touched = org.requests.slice(start)
+ .flatMap((r) => (r.operations ? r.operations : [r]))
+ .filter((r) => r.method !== 'GET' && /fieldsecurityprofile|fieldpermission|profiles_association|\$ref/i.test(r.path));
+ assert.deepEqual(touched, [], 'no write to a profile, a permission or who holds a profile');
+ assert.equal(columnSecurity(), before, 'every profile, permission, holder and solution membership is as it was');
+
+ const written = [managed, again].flatMap((d) => fs.readdirSync(d.out, { recursive: true }).map((f) => path.join(d.out, f)))
+ .filter((f) => fs.statSync(f).isFile()).map((f) => fs.readFileSync(f, 'utf8'));
+ const printed = [managed, again].flatMap((d) => [d.said, JSON.stringify(d.payload)]);
+ for (const [what, canary] of Object.entries(CANARY)) {
+ for (const text of [...written, ...printed]) assert.equal(text.toLowerCase().includes(canary.toLowerCase()), false, `${what} appears in what the download wrote or printed`);
+ }
+ assert.deepEqual(org.unexpected, []);
+});
+// Protected configuration (configurationIdentity "stable-v1") end to end on the strict lifecycle org made with its configuration tables:
+// the gated build binds canary values and a connection from deployment settings; the CLI's own download main — its real producer, not a
+// stand-in — restores each proved item; the downloaded spec reloads, validates and rebuilds completely (every phase, publish and
+// verify); and a second download writes the same bytes. The rebuild sends no write to a configuration row or a solution membership, the
+// download leaves the binding store and the build's folder as they were, and no value, default, value schema or connection appears in
+// anything either download wrote or printed.
+const SP = '/providers/Microsoft.PowerApps/apis/shared_sharepointonline';
+const CONFIG_CANARY = {
+ value: 'canary-life-value-5d2a',
+ siteValue: 'canary-life-site-7c31',
+ default: 'canary-life-default-0e94',
+ jsonDefault: 'canary-life-jsondefault-61bf',
+ schema: 'canary-life-schema-a83e',
+ connection: 'canary-life-conn-4b07',
+};
+function configuredSpec() {
+ return {
+ ...stableSpec(), minimumPluginVersion: '2.25.0', configurationIdentity: 'stable-v1',
+ environmentVariables: [
+ { schemaName: 'contoso_ApiBase', type: 'string', name: 'API base', description: 'Base address', defaultValue: `https://${CONFIG_CANARY.default}.contoso.example`, isRequired: true },
+ { schemaName: 'contoso_Shape', type: 'json', defaultValue: `{"k":"${CONFIG_CANARY.jsonDefault}"}`, valueSchema: `{"type":"object","title":"${CONFIG_CANARY.schema}"}` },
+ { schemaName: 'contoso_Site', type: 'dataSource', connectorId: SP, parameterKey: 'dataset' },
+ { schemaName: 'contoso_List', type: 'dataSource', connectorId: SP, parameterKey: 'table', parentSchemaName: 'contoso_Site' },
+ ],
+ connectionReferences: [{ logicalName: 'contoso_sp', connectorId: SP, name: 'SharePoint', description: 'Lists' }],
+ customApis: [{ uniqueName: 'contoso_Ping', binding: 'global', requestParameters: [{ uniqueName: 'In', type: 'string' }], responseProperties: [{ uniqueName: 'Out', type: 'string' }] }],
+ };
+}
+const CONFIG_SETS = ['environmentvariabledefinitions', 'environmentvariablevalues', 'connectionreferences', 'customapis', 'customapirequestparameters', 'customapiresponseproperties'];
+const walkFiles = (dir) => (fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walkFiles(path.join(dir, e.name)) : [path.join(dir, e.name)])) : []);
+const folderBytes = (dir) => Object.fromEntries(walkFiles(dir).map((f) => [path.relative(dir, f), fs.readFileSync(f).toString('base64')]));
+
+const CONFIG_REGEX = /environmentvariable|connectionreference|customapi|duplicaterule|AddSolutionComponent|solutioncomponent/i;
+const configurationWrites = (org, step) => org.requests.slice(step.mark, step.end)
+ .flatMap((r) => (r.operations ? r.operations : [r]))
+ .filter((r) => r.method !== 'GET' && CONFIG_REGEX.test(r.path));
+// Everything one request carried, as text: its path, its body and, for a batch, each of its operations.
+const sentText = (r) => JSON.stringify([r.path, Buffer.isBuffer(r.body) ? r.body.toString('latin1') : r.body, r.operations || null]);
+const UNPROVEN = ['configuration:customApi contoso_Ping: implementation (CUSTOM_API_IMPLEMENTATION_UNPROVEN)'];
+
+test('protected configuration restored by a managed download rebuilds completely with no configuration write, downloads again byte for byte, and writes no value, default, value schema or connection anywhere', async () => {
+ const spec = configuredSpec();
+ const settings = {
+ EnvironmentVariables: [
+ { SchemaName: 'contoso_ApiBase', Value: `https://${CONFIG_CANARY.value}.contoso.example` },
+ { SchemaName: 'contoso_Site', Value: `https://${CONFIG_CANARY.siteValue}.sharepoint.example/sites/a` },
+ ],
+ ConnectionReferences: [{ LogicalName: 'contoso_sp', ConnectionId: CONFIG_CANARY.connection, ConnectorId: SP }],
+ };
+ const bindings = readDeploymentBindings(settings, spec);
+ assert.deepEqual(bindings.errors, []);
+ const app = await builtLifecycle(spec, { configuration: true }, { configurationBindings: bindings, connections: [{ connectionId: CONFIG_CANARY.connection, connectorId: SP, displayName: 'SharePoint' }] });
+ const { org, harness } = app;
+ // The build verified every item it could, and a Custom API's implementation is reported unverified, not failed: no plug-in is
+ // declared for it, and nothing a build reads can prove one.
+ assert.equal(app.built.value.result.verify.ok, true);
+ assert.deepEqual(app.built.value.result.verify.missing, []);
+ assert.deepEqual(app.built.value.result.verify.unverified, UNPROVEN);
+ // The rows the build made, and the canaries it sent there: the test's own proof that each canary reached the org.
+ const rowId = (set, column, name) => {
+ const rows = [...org.rowsOf(set).values()].filter((r) => String(r.data[column]).toLowerCase() === name.toLowerCase());
+ assert.equal(rows.length, 1, `one ${set} row named ${name}`);
+ return rows[0].id;
+ };
+ const ids = {
+ contoso_apibase: rowId('environmentvariabledefinitions', 'schemaname', 'contoso_ApiBase'),
+ contoso_shape: rowId('environmentvariabledefinitions', 'schemaname', 'contoso_Shape'),
+ contoso_site: rowId('environmentvariabledefinitions', 'schemaname', 'contoso_Site'),
+ contoso_sp: rowId('connectionreferences', 'connectionreferencelogicalname', 'contoso_sp'),
+ };
+ // The filter below sees what a configuration create sends: the build's own writes are caught by it.
+ assert.ok(configurationWrites(org, app.built).length > 0);
+ const orgText = JSON.stringify(CONFIG_SETS.flatMap((set) => [...org.rowsOf(set).values()].map((r) => r.data)));
+ for (const canary of Object.values(CONFIG_CANARY)) assert.ok(orgText.includes(canary), `the build stored ${canary}`);
+
+ const before = folderBytes(harness.appDir);
+ const fromDownload = org.mark();
+ const managed = await app.download({ managed: true });
+ assert.deepEqual(folderBytes(harness.appDir), before, 'the download leaves the binding store and the build folder as they were');
+ assert.deepEqual(org.writeCounts(fromDownload), {}, 'the download sends no write');
+ // The file reloads as an App Spec the build accepts, as a maker's next build reads it.
+ const reloaded = validateAppSpec(JSON.parse(fs.readFileSync(path.join(managed.out, 'app-spec.json'), 'utf8')), { profile: 'deploy' });
+ assert.deepEqual(reloaded.errors, []);
+ assert.equal(reloaded.ok, true);
+ assert.equal(managed.spec.configurationIdentity, 'stable-v1');
+ assert.equal(managed.spec.minimumPluginVersion, '2.25.0');
+ assert.deepEqual(managed.spec.environmentVariables, [
+ { schemaName: 'contoso_ApiBase', type: 'string', name: 'API base', description: 'Base address', isRequired: true },
+ { schemaName: 'contoso_Site', type: 'dataSource', name: 'contoso_Site', isRequired: false, connectorId: SP, parameterKey: 'dataset' },
+ { schemaName: 'contoso_List', type: 'dataSource', name: 'contoso_List', isRequired: false, connectorId: SP, parameterKey: 'table', parentSchemaName: 'contoso_Site' },
+ { schemaName: 'contoso_Shape', type: 'json', name: 'contoso_Shape', isRequired: false },
+ ]);
+ assert.deepEqual(managed.spec.connectionReferences, [{ logicalName: 'contoso_sp', connectorId: SP, name: 'SharePoint', description: 'Lists' }]);
+ assert.deepEqual(managed.spec.customApis, [{
+ uniqueName: 'contoso_Ping', name: 'contoso_Ping', displayName: 'contoso_Ping', description: 'contoso_Ping', binding: 'global', isFunction: false, isPrivate: false, allowedProcessingSteps: 'none', enabledForWorkflow: false,
+ requestParameters: [{ uniqueName: 'In', type: 'string', name: 'contoso_Ping.In', displayName: 'In', description: 'In', isOptional: false }],
+ responseProperties: [{ uniqueName: 'Out', type: 'string', name: 'contoso_Ping.Out', displayName: 'Out', description: 'Out' }],
+ }]);
+ const withheld = (report) => report.withheld.map((w) => ({ kind: w.kind, id: w.id, key: w.key, fields: w.fields, code: w.code }));
+ assert.deepEqual({ restored: managed.payload.managedEnvironmentVariables.restored, omitted: managed.payload.managedEnvironmentVariables.omitted }, { restored: ['contoso_apibase', 'contoso_site', 'contoso_list', 'contoso_shape'], omitted: [] });
+ assert.deepEqual(withheld(managed.payload.managedEnvironmentVariables), [
+ { kind: 'environment variable', id: ids.contoso_apibase, key: 'contoso_apibase', fields: ['defaultValue', 'value'], code: 'fields-withheld' },
+ { kind: 'environment variable', id: ids.contoso_site, key: 'contoso_site', fields: ['value'], code: 'fields-withheld' },
+ { kind: 'environment variable', id: ids.contoso_shape, key: 'contoso_shape', fields: ['defaultValue', 'valueSchema'], code: 'fields-withheld' },
+ ]);
+ assert.deepEqual({ restored: managed.payload.managedConnectionReferences.restored, omitted: managed.payload.managedConnectionReferences.omitted }, { restored: ['contoso_sp'], omitted: [] });
+ assert.deepEqual(withheld(managed.payload.managedConnectionReferences), [{ kind: 'connection reference', id: ids.contoso_sp, key: 'contoso_sp', fields: ['connection'], code: 'fields-withheld' }]);
+ assert.deepEqual(managed.payload.managedCustomApis, { restored: ['contoso_ping'], omitted: [] });
+
+ // The complete rebuild of what the download wrote: every phase, publish and verify, with no deployment settings. The values the
+ // download left out stay as they are in the service, and the Custom API's implementation is still unverified, not failed.
+ const restoredRebuild = await app.rebuild(managed);
+ assert.deepEqual(configurationWrites(org, restoredRebuild), [], 'no write to a configuration row or a solution membership');
+ assert.deepEqual(restoredRebuild.value.result.verify.missing, []);
+ assert.deepEqual(restoredRebuild.value.result.verify.unverified, UNPROVEN);
+ // A rebuild of the plain download of the same app over the same workspace is the baseline: the restored items add no write to it.
+ const plain = await app.download({ managed: false });
+ assert.equal(plain.spec.environmentVariables, undefined);
+ const plainRebuild = await app.rebuild(plain);
+ assert.deepEqual(restoredRebuild.writes, plainRebuild.writes);
+ assert.deepEqual(publishesOf(org, restoredRebuild), publishesOf(org, plainRebuild));
+
+ const beforeAgain = folderBytes(harness.appDir);
+ const again = await app.download({ managed: true });
+ assert.deepEqual(folderBytes(harness.appDir), beforeAgain);
+ assert.equal(again.text, managed.text, 'a second managed download writes the same spec, byte for byte');
+
+ // No canary in anything either managed download wrote or printed, or in anything sent from the first download on (the rebuilds).
+ const written = [
+ ['managed stream', managed.said], ['managed result', JSON.stringify(managed.payload)], ['second stream', again.said], ['second result', JSON.stringify(again.payload)],
+ ...[managed.out, again.out].flatMap((dir) => walkFiles(dir).map((f) => [f, fs.readFileSync(f, 'latin1')])),
+ ...org.requests.slice(fromDownload).map((r, n) => [`request ${n} ${r.method} ${r.path}`, sentText(r)]),
+ ];
+ for (const [where, text] of written) for (const canary of Object.values(CONFIG_CANARY)) assert.ok(!text.includes(canary), `${canary} in ${where}`);
+ assert.deepEqual(org.unexpected, []);
+});
+
+// A page that names a connection reference makes a rebuild gate the page on the reference's binding, proven against the environment's
+// connections (configuration-artifacts.js observe): the connection must be there and be one of the connector the reference names. A
+// connection id on the row is not that proof. So a managed download restores a reference a page names only when the same proof holds
+// as it downloads; otherwise it names it `page-unready` and leaves it out, as a plain download does, and the rebuild writes the page.
+test('a reference a page names is restored only when the connections prove it bound to its connector; with none, or a connection of another connector, it is left out and the rebuild writes the page', async () => {
+ const SQL = '/providers/Microsoft.PowerApps/apis/shared_sql';
+ const spec = configuredSpec();
+ spec.pages = [{ key: 'preview', name: 'Preview', purpose: 'Preview items', dataSources: ['contoso_item'], source: { kind: 'tsx', codeFile: 'KitchenPage.tsx' }, connectorBindings: [{ logicalName: 'contoso_sp', connectorId: SP }] }];
+ spec.appShell.areas[0].groups[0].subAreas.push({ page: 'preview', title: 'Preview' });
+ const usable = [{ connectionId: CONFIG_CANARY.connection, connectorId: SP, displayName: 'SharePoint' }];
+ const bindings = readDeploymentBindings({ ConnectionReferences: [{ LogicalName: 'contoso_sp', ConnectionId: CONFIG_CANARY.connection, ConnectorId: SP }] }, spec);
+ assert.deepEqual(bindings.errors, []);
+ const app = await builtLifecycle(spec, { configuration: true }, { configurationBindings: bindings, connections: usable });
+ const { org } = app;
+ const referenceRows = () => JSON.stringify([...org.rowsOf('connectionreferences').values()].map((r) => r.data));
+ const rowsBefore = referenceRows();
+ const fromDownload = org.mark();
+ const reason = require('../lib/managed-restore-report.js').REASONS['page-unready'];
+ const left = (dl) => dl.payload.managedConnectionReferences.omitted.map((o) => [o.key, o.code, o.reason]);
+
+ // The connection is there and is one of the reference's connector: restored, and its rebuild writes the page through the gate.
+ const bound = await app.download({ managed: true, connections: usable });
+ assert.deepEqual(bound.payload.managedConnectionReferences.restored, ['contoso_sp']);
+ assert.deepEqual(left(bound), []);
+ assert.deepEqual(bound.spec.connectionReferences, [{ logicalName: 'contoso_sp', connectorId: SP, name: 'SharePoint', description: 'Lists' }]);
+ const boundRebuild = await app.rebuild(bound, { connections: usable });
+ assert.deepEqual(configurationWrites(org, boundRebuild), []);
+
+ // The connection is gone before the download begins, while the row still holds its id: left out, and the complete rebuild of what
+ // the download wrote, against the same (empty) connections, writes the page as the rebuild of the plain download does.
+ const none = [];
+ const unready = await app.download({ managed: true, connections: none });
+ assert.deepEqual(unready.payload.managedConnectionReferences.restored, []);
+ assert.deepEqual(left(unready), [['contoso_sp', 'page-unready', reason]]);
+ assert.equal(unready.spec.connectionReferences, undefined);
+ assert.match(unready.said, /WARNING: managed connection reference contoso_sp was not restored: a page of the app names it/);
+ assert.deepEqual(unready.payload.managedCustomApis, { restored: ['contoso_ping'], omitted: [] });
+ const unreadyRebuild = await app.rebuild(unready, { connections: none });
+ assert.deepEqual(configurationWrites(org, unreadyRebuild), []);
+ const plain = await app.download({ managed: false });
+ await app.rebuild(plain, { connections: none });
+
+ // The connection id on the row is a connection of another connector: not a binding the page can use.
+ const other = await app.download({ managed: true, connections: [{ connectionId: CONFIG_CANARY.connection, connectorId: SQL, displayName: 'SQL' }] });
+ assert.deepEqual(other.payload.managedConnectionReferences.restored, []);
+ assert.deepEqual(left(other), [['contoso_sp', 'page-unready', reason]]);
+ assert.equal(other.spec.connectionReferences, undefined);
+
+ assert.equal(referenceRows(), rowsBefore, 'the reference row is as the build left it');
+ const written = [
+ ...[bound, other, unready].flatMap((dl) => [[`${dl.out} stream`, dl.said], [`${dl.out} result`, JSON.stringify(dl.payload)], ...walkFiles(dl.out).map((f) => [f, fs.readFileSync(f, 'latin1')])]),
+ ...org.requests.slice(fromDownload).map((r, n) => [`request ${n} ${r.method} ${r.path}`, sentText(r)]),
+ ];
+ for (const [where, text] of written) for (const canary of Object.values(CONFIG_CANARY)) assert.ok(!text.includes(canary), `${canary} in ${where}`);
+ assert.deepEqual(org.unexpected, []);
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/download-managed-views-charts.test.js b/plugins/model-apps/scripts/tests/download-managed-views-charts.test.js
new file mode 100644
index 000000000..80c922be9
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/download-managed-views-charts.test.js
@@ -0,0 +1,549 @@
+'use strict';
+// The explicit managed download (download-model-app.js main, --include-managed --managed-manifest <store>) over the build that made
+// the store: a stable view and chart (createIdentity "stable-v1") built into a fake Dataverse by the real build and the real SDK, then
+// downloaded through main with only its connections replaced. runDownload answers what the plain download of this app hydrates: no
+// views[] or charts[], and the view and chart in the not-round-tripped inventory, by id.
+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 } = require('../lib/sdk-build.js');
+const { createPublicationBarrier } = require('../lib/publication-barrier.js');
+const { PREFIX } = require('../lib/managed-bindings.js');
+const { main: downloadMain, notRoundTrippedSummary, notRoundTrippedWarning } = require('../download-model-app.js');
+const { createFakeBuildOrg } = require('./helpers/fake-app-build-org.js');
+const { gatedClient } = require('./helpers/gated-fake-client.js');
+
+const dirs = [];
+test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });
+function newDir() {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-managed-vc-'));
+ dirs.push(dir);
+ return dir;
+}
+
+const ENTITIES = {
+ contoso_item: { attributes: { contoso_name: 'String', contoso_code: 'String', contoso_kind: 'Picklist', contoso_ownerid: 'Lookup' } },
+ contoso_owner: { attributes: { contoso_name: 'String', contoso_rank: 'Integer' } },
+};
+const SOLUTION = 'ContosoStable';
+const APP = 'contoso_stableids';
+const APP_ID = '00000000-0000-4000-8000-00000000a111';
+
+function makeSpec(extra = {}) {
+ return {
+ solution: { uniqueName: SOLUTION, displayName: 'Contoso Stable', publisherPrefix: 'contoso' },
+ app: { name: 'Stable Ids', uniqueName: APP },
+ entities: [{
+ schemaName: 'contoso_item', displayName: 'Item', existing: true, primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' },
+ columns: [{ schemaName: 'contoso_code', displayName: 'Code', type: 'Text' }, { schemaName: 'contoso_kind', displayName: 'Kind', type: 'Choice', options: [{ label: 'A', value: 100000000 }, { label: 'B', value: 100000001 }] }],
+ }],
+ views: [{ entity: 'contoso_item', name: 'Declared Items', reconcile: 'declared', columns: ['contoso_name', 'contoso_code'] }],
+ charts: [{ entity: 'contoso_item', name: 'By Kind', chartType: 'Pie', groupBy: 'contoso_kind', reconcile: 'declared' }],
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Records', subAreas: [{ entity: 'contoso_item', title: 'Items' }] }] }] },
+ ...extra,
+ };
+}
+const stableSpec = (extra) => makeSpec({ createIdentity: 'stable-v1', minimumPluginVersion: '2.21.0', ...extra });
+
+// The build that keeps the store: views and charts only, published, as the CLI's build leaves them (its publish phase settles the
+// chart's table publish; the views phase publishes its own).
+async function build(org, dir, spec, phases = ['views', 'charts', 'publish']) {
+ const barrier = createPublicationBarrier();
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: org.origin, httpClient: gatedClient(org, barrier, null) });
+ await sdk.initWorkspace();
+ const out = await runSdkBuild(spec, { sdk, apply: true, publish: true, workspaceDir: dir, appDir: dir, env: org.origin, warn: () => {}, phases, publicationBarrier: barrier });
+ return { out, sdk };
+}
+const storeFileOf = (dir) => path.join(dir, fs.readdirSync(dir).find((f) => f.startsWith(PREFIX)));
+
+// What a plain download of this app hydrates: the spec with no views[] or charts[] (a downloaded spec carries none), and the
+// not-round-tripped inventory naming the view and chart the app holds.
+function plainDownload(built) {
+ const { createIdentity, minimumPluginVersion, ...spec } = makeSpec({ views: [], charts: [] });
+ void createIdentity; void minimumPluginVersion;
+ const inventory = {
+ ...(built.view ? { views: [{ id: built.view, name: 'Declared Items', entity: 'contoso_item' }] } : {}),
+ ...(built.chart ? { charts: [{ id: built.chart, name: 'By Kind', entity: 'contoso_item' }] } : {}),
+ };
+ return { spec, inventory };
+}
+
+// download-model-app.js main with its connections replaced; runDownload keeps runDownload's contract for the report: printed by it
+// unless main asks it to defer (`deferReport`), then handed back as its parts.
+async function download(org, out, argv, { downloaded, ...extra } = {}) {
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(newDir()), instanceUrl: org.origin, httpClient: org.httpClient });
+ await sdk.initWorkspace();
+ const dl = Object.create(sdk);
+ dl.queryRecords = async (table, o) => (table === 'appmodule' ? [{ uniquename: APP }] : sdk.queryRecords(table, o));
+ const asked = [];
+ const emitted = [];
+ const said = [];
+ const printed = [];
+ const mark = org.calls.length;
+ await downloadMain({
+ argv: ['--env', org.origin, '--app', APP_ID, '--out', out, ...argv],
+ stderr: { write: (text) => { said.push(String(text)); return true; } },
+ exit: () => {},
+ emitResult: (ok, payload) => emitted.push({ ok, payload }),
+ preflightAuth: async () => ({ ok: true }),
+ makeDownloadSdk: async () => ({ sdk: dl, cleanup() {} }),
+ makeGenpageSdk: () => ({}),
+ runDownload: async (args) => {
+ asked.push(args);
+ const spec = JSON.parse(JSON.stringify(downloaded.spec));
+ const notRoundTripped = notRoundTrippedSummary(downloaded.inventory);
+ if (!args.deferReport && notRoundTripped) printed.push(notRoundTrippedWarning(notRoundTripped));
+ return {
+ ok: true, spec, pages: [], entities: [], webResources: [], droppedSubareas: 0, droppedSubareaDetails: [], notRoundTripped,
+ ...(args.deferReport ? { deferredReport: { inventory: downloaded.inventory, membershipNotes: [] } } : {}),
+ };
+ },
+ ...extra,
+ });
+ const specFile = path.join(out, 'app-spec.json');
+ const calls = org.calls.slice(mark);
+ return { asked, emitted, said: said.join(''), printed: printed.join(''), calls, writes: calls.filter((c) => c.method !== 'GET'), written: fs.existsSync(specFile) ? JSON.parse(fs.readFileSync(specFile, 'utf8')) : null };
+}
+
+async function builtApp(extra) {
+ const org = createFakeBuildOrg({ entities: ENTITIES, solution: { uniqueName: SOLUTION } });
+ const dir = newDir();
+ const spec = stableSpec(extra);
+ const { out } = await build(org, dir, spec);
+ const built = { view: out.created.views['contoso_item|Declared Items'], chart: out.created.charts['contoso_item|By Kind'] };
+ assert.ok((!spec.views.length || built.view) && (!spec.charts.length || built.chart), JSON.stringify(out.created));
+ return { org, dir, built, flags: ['--include-managed', '--managed-manifest', storeFileOf(dir)] };
+}
+
+// --- the report seam ---------------------------------------------------------------------------------------------------------------
+
+test('the managed download asks runDownload to defer the not-round-tripped report and prints it once, after the restore, less what it restored; the plain one does not ask', async () => {
+ const { org, built, flags } = await builtApp();
+ const downloaded = plainDownload(built);
+ // A stock view no store proves: it stays in the report.
+ const stock = { id: '00000000-0000-4000-8000-0000000000aa', name: 'Active Items', entity: 'contoso_item' };
+ downloaded.inventory.views.push(stock);
+ const managed = await download(org, newDir(), flags, { downloaded });
+ assert.equal(managed.emitted.length, 1);
+ assert.equal(managed.emitted[0].ok, true, JSON.stringify(managed.emitted) + managed.said);
+ assert.equal(managed.asked[0].deferReport, true);
+ // The declared view and chart are restored into views[] and charts[], so only the stock view is still reported as left out.
+ const left = notRoundTrippedSummary({ views: [stock] });
+ const warning = notRoundTrippedWarning(notRoundTrippedSummary(downloaded.inventory));
+ assert.equal(managed.printed, '', 'runDownload printed nothing itself');
+ assert.equal(managed.said.split(notRoundTrippedWarning(left)).length - 1, 1, `main printed the report once: ${managed.said}`);
+ assert.equal(managed.said.includes(warning), false, 'and never the report that still names what was restored');
+ assert.deepEqual(managed.emitted[0].payload.notRoundTripped, left);
+
+ const plain = await download(org, newDir(), [], { downloaded });
+ assert.equal(plain.emitted[0].ok, true, JSON.stringify(plain.emitted));
+ assert.equal('deferReport' in plain.asked[0], false, 'the plain download asks runDownload exactly what it did');
+ assert.equal(plain.printed, warning, 'runDownload printed the report, as it always did');
+ assert.equal(plain.said.includes(warning), false, 'and main did not print it again');
+ assert.deepEqual(plain.emitted[0].payload.notRoundTripped, notRoundTrippedSummary(downloaded.inventory));
+});
+
+test('a store rewritten while the managed download reads it stops the download before anything is written', async () => {
+ const { org, dir, built, flags } = await builtApp();
+ const { validateAppSpec } = require('../lib/app-spec.js');
+ const file = storeFileOf(dir);
+ let touched = false;
+ const out = newDir();
+ const res = await download(org, out, flags, {
+ downloaded: plainDownload(built),
+ // A build rewriting the store between the restore's first read and the publication of the download (JSON-equal, other bytes).
+ validateAppSpec: (s, o) => {
+ if (!touched) { fs.appendFileSync(file, '\n'); touched = true; }
+ return validateAppSpec(s, o);
+ },
+ });
+ assert.ok(touched);
+ assert.equal(res.emitted.length, 1);
+ assert.equal(res.emitted[0].ok, false, JSON.stringify(res.emitted));
+ assert.equal(res.emitted[0].payload.code, 'managed-manifest-changed');
+ assert.match(res.emitted[0].payload.error, /changed while this download read it.*Nothing was written\.$/s);
+ assert.deepEqual(fs.readdirSync(out), [], 'no spec, baseline or fragments file');
+ assert.deepEqual(res.writes, [], 'the download writes nothing to the service');
+});
+
+// --- managed views -----------------------------------------------------------------------------------------------------------------
+
+const { viewDeclarationFromLive } = require('../lib/declared-view-io.js');
+const VIEW_KEY = 'contoso_item/Declared Items';
+// A declared view using every part a declaration can say: widths, a joined-table column, sort on the join and the base table, the
+// default active filter, an `in` list written partly as a label, a condition with no value, one on the join, and the join's own filter.
+const RICH_VIEW = {
+ entity: 'contoso_item', name: 'Declared Items', reconcile: 'declared', description: 'Items by kind',
+ columns: ['contoso_name', { name: 'contoso_code', width: 150 }, { name: 'own.contoso_name', relatedEntity: 'own', width: 120 }],
+ sort: [{ attr: 'contoso_name', relatedEntity: 'own' }, { attr: 'contoso_code', dir: 'desc' }],
+ filters: [{ attr: 'contoso_kind', op: 'in', values: ['A', 100000001] }, { attr: 'contoso_code', op: 'not-null' }, { attr: 'contoso_rank', op: 'gt', value: 3, relatedEntity: 'own' }],
+ linkEntities: [{ name: 'contoso_owner', from: 'contoso_ownerid', to: 'contoso_ownerid', alias: 'own', linkType: 'outer', filters: [{ attr: 'contoso_rank', op: 'ge', value: 1 }] }],
+};
+const nonGet = (calls) => calls.filter((c) => c.method !== 'GET');
+const savedQueryWrites = (calls) => nonGet(calls).filter((c) => /savedquer/i.test(c.path));
+// Rewrite the view group of the store file in place (a test of what the restore makes of a group it cannot trust).
+function editViewGroup(dir, edit) {
+ const file = storeFileOf(dir);
+ const store = JSON.parse(fs.readFileSync(file, 'utf8'));
+ edit(store.groups.find((g) => g.family === 'view'));
+ fs.writeFileSync(file, JSON.stringify(store, null, 2));
+}
+
+test('a view a stable build created is downloaded as the declaration that rebuilds it, pinned to its id, and is no longer reported as left out', async () => {
+ const { org, dir, built, flags } = await builtApp({ views: [RICH_VIEW] });
+ const downloaded = plainDownload(built);
+ const stock = { id: '00000000-0000-4000-8000-0000000000aa', name: 'Active Items', entity: 'contoso_item' };
+ downloaded.inventory.views.push(stock);
+ const res = await download(org, newDir(), flags, { downloaded });
+ assert.equal(res.emitted[0].ok, true, JSON.stringify(res.emitted) + res.said);
+ assert.deepEqual(res.written.views, [{
+ entity: 'contoso_item', name: 'Declared Items', reconcile: 'declared', description: 'Items by kind',
+ columns: [{ name: 'contoso_name', width: 100 }, { name: 'contoso_code', width: 150 }, { name: 'own.contoso_name', relatedEntity: 'own', width: 120 }],
+ sort: [{ attr: 'contoso_name', relatedEntity: 'own' }, { attr: 'contoso_code', dir: 'desc' }],
+ // The active filter the build added is written out as a condition, with activeOnly false: never the default, re-guessed.
+ activeOnly: false,
+ filters: [
+ { attr: 'statecode', op: 'eq', value: 0 },
+ { attr: 'contoso_code', op: 'not-null' },
+ { attr: 'contoso_rank', op: 'gt', value: 3, relatedEntity: 'own' },
+ { attr: 'contoso_kind', op: 'in', values: [100000000, 100000001] },
+ ],
+ linkEntities: [{ name: 'contoso_owner', from: 'contoso_ownerid', to: 'contoso_ownerid', alias: 'own', linkType: 'outer', filters: [{ attr: 'contoso_rank', op: 'ge', value: 1 }] }],
+ viewId: built.view,
+ }]);
+ assert.equal(res.written.createIdentity, 'stable-v1');
+ assert.equal(res.written.minimumPluginVersion, '2.21.0');
+ assert.deepEqual(res.emitted[0].payload.managedViews, { restored: [VIEW_KEY], omitted: [] });
+ // The restored view (and the restored chart) leave the report; the stock view stays in it.
+ const left = { views: [stock] };
+ assert.deepEqual(res.emitted[0].payload.notRoundTripped, notRoundTrippedSummary(left));
+ assert.equal(res.said.split(notRoundTrippedWarning(notRoundTrippedSummary(left))).length - 1, 1, res.said);
+ assert.deepEqual(res.writes, [], 'the download writes nothing to the service');
+
+ // A rebuild from the downloaded spec, through the build's own workspace and store and with its publish phase, finds nothing to
+ // change: no view write, and no publish of the view's table (the view is bound and proved as it is, so it owes its table nothing).
+ const mark = org.calls.length;
+ const rebuilt = await build(org, dir, res.written);
+ assert.equal(rebuilt.out.ok, true, JSON.stringify(rebuilt.out.steps || rebuilt.out));
+ assert.deepEqual(savedQueryWrites(org.calls.slice(mark)), []);
+ assert.deepEqual(org.publishLog(mark), []);
+ // And from a new folder with no store, the pin alone names the row, which already holds the declaration: that build writes nothing.
+ const reconcileOnly = ['views', 'charts'];
+ const fresh = org.calls.length;
+ await build(org, newDir(), res.written, reconcileOnly);
+ assert.deepEqual(savedQueryWrites(org.calls.slice(fresh)), []);
+ assert.deepEqual(org.publishLog(fresh), []);
+ // A declaration that changes the view still has its table published: the rebuild saves the view, and the saved view owes it.
+ const changed = { ...res.written, views: [{ ...res.written.views[0], description: 'Items by kind, edited' }] };
+ const edit = org.calls.length;
+ const edited = await build(org, dir, changed);
+ assert.equal(edited.out.ok, true, JSON.stringify(edited.out.steps || edited.out));
+ assert.notDeepEqual(savedQueryWrites(org.calls.slice(edit)), []);
+ assert.deepEqual(org.publishLog(edit), ['tables contoso_item']);
+});
+
+test('two proved views with one name on one table are both restored, each under its own key and id', async () => {
+ const views = [
+ { entity: 'contoso_item', name: 'Declared Items', key: 'first', reconcile: 'declared', columns: ['contoso_name'] },
+ { entity: 'contoso_item', name: 'Declared Items', key: 'second', reconcile: 'declared', columns: ['contoso_name', 'contoso_code'] },
+ ];
+ const { org, dir, built, flags } = await builtApp({ views, charts: [] });
+ const store = JSON.parse(fs.readFileSync(storeFileOf(dir), 'utf8'));
+ const ids = store.groups.filter((g) => g.family === 'view').map((g) => g.records[0].id);
+ assert.equal(new Set(ids).size, 2, JSON.stringify(store.groups));
+ const downloaded = plainDownload(built);
+ downloaded.inventory.views = ids.map((id) => ({ id, name: 'Declared Items', entity: 'contoso_item' }));
+ const res = await download(org, newDir(), flags, { downloaded });
+ assert.equal(res.emitted[0].ok, true, JSON.stringify(res.emitted) + res.said);
+ assert.equal(res.written.views.length, 2, JSON.stringify(res.written.views));
+ assert.deepEqual(res.written.views.map((v) => [v.key, v.columns.map((c) => c.name)]).sort(), [['first', ['contoso_name']], ['second', ['contoso_name', 'contoso_code']]]);
+ assert.deepEqual(res.written.views.map((v) => v.viewId).sort(), [...ids].sort());
+ assert.deepEqual(res.emitted[0].payload.managedViews, { restored: ['first', 'second'], omitted: [] });
+ assert.equal(res.emitted[0].payload.notRoundTripped, undefined, 'both views were restored, so neither is reported as left out');
+});
+
+test('a managed download with no view or chart to restore or leave out adds no managedViews or managedCharts to its result', async () => {
+ // A valid store that holds no group: the build's own, emptied (a build with no view or chart keeps no store at all).
+ const { org, dir, built, flags } = await builtApp({ charts: [] });
+ const file = storeFileOf(dir);
+ fs.writeFileSync(file, JSON.stringify({ ...JSON.parse(fs.readFileSync(file, 'utf8')), groups: [] }, null, 2));
+ const res = await download(org, newDir(), flags, { downloaded: plainDownload(built) });
+ assert.equal(res.emitted[0].ok, true, JSON.stringify(res.emitted) + res.said);
+ assert.equal('managedViews' in res.emitted[0].payload, false, JSON.stringify(res.emitted[0].payload));
+ assert.equal('managedCharts' in res.emitted[0].payload, false, JSON.stringify(res.emitted[0].payload));
+});
+
+test('a managed view the restore cannot prove is left out of views[] with a fixed reason and stays in the report', async (t) => {
+ const cases = [
+ ['edited since its build proved it', 'changed', async ({ org, built }) => {
+ await org.httpClient.patch(`${org.origin}/api/data/v9.2/savedqueries(${built.view})`, { description: 'Edited in the maker portal' });
+ }],
+ ['renamed and the rename not published', 'unpublished-changes', async ({ org, built }) => {
+ await org.httpClient.patch(`${org.origin}/api/data/v9.2/savedqueries(${built.view})`, { name: 'Renamed Items' });
+ }],
+ ['adopted, not created, by its build', 'not-created', async ({ dir }) => editViewGroup(dir, (g) => { g.records[0].origin = 'adopted'; })],
+ // The store says the table's publish is still owed (the shape a build leaves after a saved, unpublished write).
+ ['whose publish is still owed', 'publication-unsettled', async ({ dir }) => editViewGroup(dir, (g) => { g.publication.state = 'owed'; g.publication.dispatchToken = null; })],
+ ['deleted since', 'missing', async ({ org, built }) => {
+ org.intercept((c) => c.method === 'GET' && c.path.includes(`savedqueries(${built.view})`), () => ({ status: 404, headers: {}, body: { error: { code: '0x80040217', message: 'Does Not Exist' } } }));
+ }],
+ ];
+ for (const [what, code, provoke] of cases) {
+ await t.test(what, async () => {
+ // No chart, so a restored chart cannot opt the spec into stable ids either.
+ const app = await builtApp({ charts: [] });
+ await provoke(app);
+ const downloaded = plainDownload(app.built);
+ const res = await download(app.org, newDir(), app.flags, { downloaded });
+ assert.equal(res.emitted[0].ok, true, JSON.stringify(res.emitted) + res.said);
+ const omitted = res.emitted[0].payload.managedViews.omitted;
+ assert.equal(omitted.length, 1, JSON.stringify(omitted));
+ assert.equal(omitted[0].code, code);
+ assert.equal(omitted[0].key, VIEW_KEY);
+ assert.equal(omitted[0].id, app.built.view);
+ assert.doesNotMatch(JSON.stringify(omitted), /Edited in the maker portal|Does Not Exist/, 'a reason never carries what the service said');
+ assert.match(res.said, new RegExp(`WARNING: managed view ${VIEW_KEY} was not restored: `));
+ assert.deepEqual(res.written.views, []);
+ assert.equal(res.written.createIdentity, undefined, 'nothing restored, so the spec is not opted into stable ids');
+ assert.deepEqual(res.emitted[0].payload.notRoundTripped, notRoundTrippedSummary(downloaded.inventory));
+ });
+ }
+});
+
+test('viewDeclarationFromLive refuses a view whose query a declaration cannot say, and never flattens a filter tree', () => {
+ const view = (over = {}) => ({
+ id: '00000000-0000-4000-8000-0000000000bb', name: 'V', entityLogicalName: 'contoso_item', queryType: 0,
+ columns: [{ name: 'contoso_name', width: 100, order: 0 }],
+ filters: { type: 'and', conditions: [{ attribute: 'contoso_code', operator: 'not-null' }], groups: [] },
+ sort: [],
+ fetchBag: { a: [['version', '1.0']], c: [{ i: 0, node: { n: 'entity', a: [['name', 'contoso_item']], c: [
+ { n: 'attribute', a: [['name', 'contoso_name']], c: [] },
+ { n: 'filter', a: [['type', 'and']], c: [{ n: 'condition', a: [['attribute', 'contoso_code'], ['operator', 'not-null']], c: [] }] },
+ ] } }] },
+ ...over,
+ });
+ assert.deepEqual(viewDeclarationFromLive(view(), { key: 'contoso_item/V' }).declaration, {
+ entity: 'contoso_item', name: 'V', reconcile: 'declared', columns: [{ name: 'contoso_name', width: 100 }], activeOnly: false, filters: [{ attr: 'contoso_code', op: 'not-null' }],
+ });
+ assert.equal(viewDeclarationFromLive(view(), { key: 'custom-key' }).declaration.key, 'custom-key', 'a key that is not the default is kept');
+ const tree = (groups) => ({ type: 'and', conditions: [], groups });
+ const refused = {
+ 'an OR of two columns': { filters: tree([{ type: 'or', conditions: [{ attribute: 'a', operator: 'eq', value: '1' }, { attribute: 'b', operator: 'eq', value: '1' }], groups: [] }]) },
+ 'an OR of mixed operators': { filters: tree([{ type: 'or', conditions: [{ attribute: 'a', operator: 'eq', value: '1' }, { attribute: 'a', operator: 'ne', value: '2' }], groups: [] }]) },
+ 'a nested group': { filters: tree([{ type: 'or', conditions: [{ attribute: 'a', operator: 'eq', value: '1' }], groups: [{ type: 'and', conditions: [], groups: [] }] }]) },
+ 'an OR at the top': { filters: { type: 'or', conditions: [], groups: [] } },
+ 'a quick-find filter': { fetchBag: { a: [], c: [{ i: 0, node: { n: 'entity', a: [], c: [
+ { n: 'filter', a: [['type', 'and']], c: [{ n: 'condition', a: [['attribute', 'contoso_code'], ['operator', 'not-null']], c: [] }] },
+ { n: 'filter', a: [['type', 'or'], ['isquickfindfields', '1']], c: [{ n: 'condition', a: [['attribute', 'contoso_name'], ['operator', 'like'], ['value', '{0}']], c: [] }] },
+ ] } }] } },
+ 'an aggregate query': { fetchBag: { a: [['aggregate', 'true']], c: [{ i: 0, node: { n: 'entity', a: [], c: [{ n: 'filter', a: [], c: [{ n: 'condition', a: [], c: [] }] }] } }] } },
+ 'a join the typed tree does not show': { fetchBag: { a: [], c: [{ i: 0, node: { n: 'entity', a: [], c: [
+ { n: 'filter', a: [], c: [{ n: 'condition', a: [], c: [] }] }, { n: 'link-entity', a: [['name', 'x']], c: [] },
+ ] } }] } },
+ 'a column read back without its join': { columns: [{ name: 'own.contoso_name', width: 100, order: 0 }] },
+ 'a column with no width': { columns: [{ name: 'contoso_name', order: 0 }] },
+ 'a quick find view': { queryType: 4 },
+ };
+ for (const [what, over] of Object.entries(refused)) {
+ const out = viewDeclarationFromLive(view(over), { key: 'contoso_item/V' });
+ assert.equal(out.declaration, undefined, what);
+ assert.equal(typeof out.unsupported, 'string', what);
+ }
+});
+// --- managed charts ----------------------------------------------------------------------------------------------------------------
+
+const { chartDeclarationFromLive } = require('../lib/declared-chart-io.js');
+const { readSavedQueryLayerRows } = require('../lib/savedquery-published.js');
+const CHART_KEY = 'contoso_item/By Kind';
+const chartWrites = (calls) => nonGet(calls).filter((c) => /savedqueryvisualization/i.test(c.path));
+const API = (org) => `${org.origin}/api/data/v9.2`;
+const chartRow = async (org, id) => (await org.httpClient.get(`${API(org)}/savedqueryvisualizations(${id})?$select=name,description,datadescription,presentationdescription`)).body;
+const publishTable = (org) => org.httpClient.post(`${API(org)}/PublishXml`, { ParameterXml: '<importexportxml><entities><entity>contoso_item</entity></entities></importexportxml>' });
+function editChartGroup(dir, edit) {
+ const file = storeFileOf(dir);
+ const store = JSON.parse(fs.readFileSync(file, 'utf8'));
+ edit(store.groups.find((g) => g.family === 'chart'));
+ fs.writeFileSync(file, JSON.stringify(store, null, 2));
+}
+// A maker edit the build then proved again: the store's confirmed publish names the saved layer as it is now, so only the restore's
+// own checks (not the publish proof) can refuse the chart.
+async function reproveChart({ org, dir }) {
+ const client = { get: (p) => org.httpClient.get(`${API(org)}${p}`) };
+ const store = JSON.parse(fs.readFileSync(storeFileOf(dir), 'utf8'));
+ const { savedSha256 } = await readSavedQueryLayerRows('chart', client, store.groups.find((g) => g.family === 'chart'));
+ editChartGroup(dir, (g) => { g.publication.desiredSha256 = savedSha256; });
+}
+
+test('a chart a stable build created is downloaded as the declaration that rebuilds it, and a rebuild through the store writes nothing, not even to a namesake', async () => {
+ const { org, dir, built, flags } = await builtApp({ views: [] });
+ const downloaded = plainDownload(built);
+ const res = await download(org, newDir(), flags, { downloaded });
+ assert.equal(res.emitted[0].ok, true, JSON.stringify(res.emitted) + res.said);
+ assert.deepEqual(res.written.charts, [{ entity: 'contoso_item', name: 'By Kind', reconcile: 'declared', chartType: 'Pie', groupBy: 'contoso_kind', measure: 'count' }]);
+ assert.equal(res.written.createIdentity, 'stable-v1');
+ assert.equal(res.written.minimumPluginVersion, '2.21.0');
+ assert.deepEqual(res.emitted[0].payload.managedCharts, { restored: [CHART_KEY], omitted: [] });
+ assert.equal(notRoundTrippedSummary({}), null);
+ assert.equal(res.emitted[0].payload.notRoundTripped, undefined, 'nothing is left to report');
+ assert.doesNotMatch(res.said, /managed chart|does not reconstruct/);
+ assert.deepEqual(res.writes, [], 'the download writes nothing to the service');
+
+ // A chart with the same name on the same table, made after the build: the store names the exact row, so it is never the one bound.
+ const before = await chartRow(org, built.chart);
+ const namesakeRes = await org.httpClient.post(`${API(org)}/savedqueryvisualizations`, {
+ name: 'By Kind', primaryentitytypecode: 'contoso_item', datadescription: before.datadescription, presentationdescription: before.presentationdescription,
+ });
+ assert.ok(namesakeRes.status < 300, JSON.stringify(namesakeRes));
+ const again = await download(org, newDir(), flags, { downloaded });
+ assert.deepEqual(again.written.charts, res.written.charts);
+ assert.deepEqual(again.emitted[0].payload.managedCharts, { restored: [CHART_KEY], omitted: [] });
+
+ const mark = org.calls.length;
+ await build(org, dir, res.written);
+ assert.deepEqual(chartWrites(org.calls.slice(mark)), [], 'no write to the chart or its namesake');
+ assert.deepEqual(org.publishLog(mark), []);
+ assert.deepEqual(await chartRow(org, built.chart), before, 'palette, colours and every other byte of the chart are as they were');
+});
+
+test('a managed chart the restore cannot prove is left out of charts[] with a fixed reason and stays in the report', async (t) => {
+ const patch = (org, id, body) => org.httpClient.patch(`${API(org)}/savedqueryvisualizations(${id})`, body);
+ const cases = [
+ ['edited since its build proved it', 'changed', async ({ org, built }) => { await patch(org, built.chart, { description: 'Edited in the maker portal' }); }],
+ ['renamed and the rename not published', 'unpublished-changes', async ({ org, built }) => { await patch(org, built.chart, { name: 'Renamed Kind' }); }],
+ ['renamed, published and proved again', 'key-mismatch', async (app) => {
+ await patch(app.org, app.built.chart, { name: 'Renamed Kind' });
+ await publishTable(app.org);
+ await reproveChart(app);
+ }],
+ ['given a filter the declaration cannot say, published and proved again', 'unsupported', async (app) => {
+ const { datadescription } = await chartRow(app.org, app.built.chart);
+ const filtered = datadescription.replace(/<\/entity>/, '<filter type="and"><condition attribute="contoso_code" operator="not-null" /></filter></entity>');
+ assert.notEqual(filtered, datadescription);
+ await patch(app.org, app.built.chart, { datadescription: filtered });
+ await publishTable(app.org);
+ await reproveChart(app);
+ }],
+ ['adopted, not created, by its build', 'not-created', async ({ dir }) => editChartGroup(dir, (g) => { g.records[0].origin = 'adopted'; })],
+ ['whose publish is still owed', 'publication-unsettled', async ({ dir }) => editChartGroup(dir, (g) => { g.publication.state = 'owed'; g.publication.dispatchToken = null; })],
+ ['deleted since', 'missing', async ({ org, built }) => {
+ org.intercept((c) => c.method === 'GET' && c.path.includes(`savedqueryvisualizations(${built.chart})`), () => ({ status: 404, headers: {}, body: { error: { code: '0x80040217', message: 'Does Not Exist' } } }));
+ }],
+ ];
+ for (const [what, code, provoke] of cases) {
+ await t.test(what, async () => {
+ const app = await builtApp({ views: [] });
+ await provoke(app);
+ const downloaded = plainDownload(app.built);
+ const res = await download(app.org, newDir(), app.flags, { downloaded });
+ assert.equal(res.emitted[0].ok, true, JSON.stringify(res.emitted) + res.said);
+ const omitted = res.emitted[0].payload.managedCharts.omitted;
+ assert.equal(omitted.length, 1, JSON.stringify(omitted));
+ assert.equal(omitted[0].code, code);
+ assert.equal(omitted[0].key, CHART_KEY);
+ assert.equal(omitted[0].id, app.built.chart);
+ assert.doesNotMatch(JSON.stringify(omitted), /Edited in the maker portal|Does Not Exist/, 'a reason never carries what the service said');
+ assert.match(res.said, new RegExp(`WARNING: managed chart ${CHART_KEY} was not restored: `));
+ assert.deepEqual(res.written.charts, []);
+ assert.equal(res.written.createIdentity, undefined, 'nothing restored, so the spec is not opted into stable ids');
+ assert.deepEqual(res.emitted[0].payload.notRoundTripped, notRoundTrippedSummary(downloaded.inventory));
+ assert.deepEqual(res.writes, [], 'the download writes nothing to the service');
+ });
+ }
+});
+
+// The solution of the app must hold a view or chart NOW for the restore to declare it: the store only shows the build added it once.
+// What counts is what a build counts (lib/solution-membership.js): a component row of its own, or the table held with ALL its
+// subcomponents (rootcomponentbehavior 0). A shell (2) carries none, and a membership that cannot be read is no proof either way.
+test('a managed view or chart is restored only while the solution of the app holds it, and the download never repairs membership', async (t) => {
+ const failRead = (org) => org.intercept((c) => c.method === 'GET' && /solutioncomponents/.test(c.path), () => ({ status: 500, headers: {}, body: { error: { code: '0x80040E14', message: 'Generic SQL error' } } }));
+ const drop = ({ org, built }) => { org.fake.removeMember(26, built.view); org.fake.removeMember(59, built.chart); };
+ const cases = [
+ ['each with a component row of its own', null, () => {}],
+ ['through their table held with all its subcomponents', null, (app) => { drop(app); app.org.fake.holdTable('contoso_item', 0); }],
+ ['with their table held as a shell only', 'not-in-solution', (app) => { drop(app); app.org.fake.holdTable('contoso_item', 2); }],
+ ['with their table held without its subcomponents', 'not-in-solution', (app) => { drop(app); app.org.fake.holdTable('contoso_item', 1); }],
+ ['no longer in the solution at all', 'not-in-solution', (app) => drop(app)],
+ ['whose membership cannot be read', 'membership-unknown', (app) => failRead(app.org)],
+ ['held through a table whose id cannot be resolved', 'membership-unknown', (app) => { drop(app); app.org.fake.holdTable('contoso_item', 0); app.org.fake.failTableIdReads(true); }],
+ ];
+ for (const [what, code, provoke] of cases) {
+ await t.test(what, async () => {
+ const app = await builtApp();
+ await provoke(app);
+ const downloaded = plainDownload(app.built);
+ const res = await download(app.org, newDir(), app.flags, { downloaded });
+ assert.equal(res.emitted[0].ok, true, JSON.stringify(res.emitted) + res.said);
+ assert.deepEqual(res.writes, [], 'the download writes nothing to the service, an AddSolutionComponent least of all');
+ const { managedViews, managedCharts } = res.emitted[0].payload;
+ if (!code) {
+ assert.deepEqual(managedViews, { restored: [VIEW_KEY], omitted: [] });
+ assert.deepEqual(managedCharts, { restored: [CHART_KEY], omitted: [] });
+ assert.equal(res.written.views.length, 1);
+ assert.equal(res.written.charts.length, 1);
+ return;
+ }
+ assert.deepEqual(managedViews.restored, []);
+ assert.deepEqual(managedCharts.restored, []);
+ assert.deepEqual(managedViews.omitted.map((o) => [o.key, o.id, o.code]), [[VIEW_KEY, app.built.view, code]]);
+ assert.deepEqual(managedCharts.omitted.map((o) => [o.key, o.id, o.code]), [[CHART_KEY, app.built.chart, code]]);
+ assert.doesNotMatch(JSON.stringify([managedViews, managedCharts]), /Generic SQL error/, 'a reason never carries what the service said');
+ assert.deepEqual(res.written.views, []);
+ assert.deepEqual(res.written.charts, []);
+ assert.equal(res.written.createIdentity, undefined, 'nothing restored, so the spec is not opted into stable ids');
+ assert.deepEqual(res.emitted[0].payload.notRoundTripped, notRoundTrippedSummary(downloaded.inventory));
+ });
+ }
+});
+
+test('chartDeclarationFromLive says only one count of the id by one column of the table, and refuses the rest', () => {
+ const chart = (over = {}) => ({
+ id: '00000000-0000-4000-8000-0000000000cc', name: 'By Kind', description: '', entityLogicalName: 'contoso_item', chartType: 'Column', isDefault: false,
+ series: [{ attribute: 'contoso_itemid', aggregate: 'count', alias: 'a' }], categories: [{ attribute: 'contoso_kind', alias: 'b' }],
+ presentation: { showLegend: true }, ...over,
+ });
+ assert.deepEqual(chartDeclarationFromLive(chart()).declaration, { entity: 'contoso_item', name: 'By Kind', reconcile: 'declared', chartType: 'Column', groupBy: 'contoso_kind', measure: 'count' });
+ assert.deepEqual(chartDeclarationFromLive(chart({ description: 'Items', presentation: { title: 'Kinds' } })).declaration,
+ { entity: 'contoso_item', name: 'By Kind', reconcile: 'declared', chartType: 'Column', groupBy: 'contoso_kind', measure: 'count', description: 'Items', title: 'Kinds' });
+ const refused = {
+ 'two series': { series: [{ attribute: 'contoso_itemid', aggregate: 'count' }, { attribute: 'contoso_itemid', aggregate: 'countcolumn' }] },
+ 'two categories': { categories: [{ attribute: 'contoso_kind' }, { attribute: 'contoso_code' }] },
+ 'a category grouped by date': { categories: [{ attribute: 'createdon', dateGrouping: 'month' }] },
+ 'a category on a joined table': { categories: [{ attribute: 'contoso_rank', relatedEntity: 'own' }] },
+ 'a measure on a joined table': { series: [{ attribute: 'contoso_ownerid', aggregate: 'count', relatedEntity: 'own' }] },
+ 'a measure of another column': { series: [{ attribute: 'contoso_code', aggregate: 'count' }] },
+ 'a sum': { series: [{ attribute: 'contoso_itemid', aggregate: 'sum' }] },
+ 'a chart type a declaration cannot say': { chartType: 'Radar' },
+ 'no name': { name: ' ' },
+ };
+ for (const [what, over] of Object.entries(refused)) {
+ const out = chartDeclarationFromLive(chart(over));
+ assert.equal(out.declaration, undefined, what);
+ assert.equal(typeof out.unsupported, 'string', what);
+ }
+});
+
+// --- field security profiles: reported by both downloads, restored by neither ---------------------------------------------------
+
+test('the field security profiles runDownload reports reach the result of a plain and a managed download alike, and neither declares one', async () => {
+ const { org, built, flags } = await builtApp();
+ const downloaded = plainDownload(built);
+ const omitted = [{ kind: 'fieldSecurityProfile', id: '00000000-0000-4000-8000-0000000000f1', name: 'HR', code: 'ownership-unproven', reason: 'no binding store record proves this app authored it, so it is not declared' }];
+ const runDownload = async (args) => {
+ const notRoundTripped = notRoundTrippedSummary(downloaded.inventory);
+ return {
+ ok: true, spec: JSON.parse(JSON.stringify(downloaded.spec)), pages: [], entities: [], webResources: [], droppedSubareas: 0, droppedSubareaDetails: [], notRoundTripped,
+ fieldSecurityProfiles: { omitted },
+ ...(args.deferReport ? { deferredReport: { inventory: downloaded.inventory, membershipNotes: [] } } : {}),
+ };
+ };
+ for (const argv of [[], flags]) {
+ const run = await download(org, newDir(), argv, { downloaded, runDownload });
+ assert.equal(run.emitted[0].ok, true, JSON.stringify(run.emitted) + run.said);
+ assert.deepEqual(run.emitted[0].payload.fieldSecurityProfiles, { omitted });
+ assert.equal('fieldSecurityProfiles' in run.written, false);
+ assert.equal(run.writes.some((c) => /fieldsecurityprofile|fieldpermission/i.test(c.path)), false);
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/download-model-app.test.js b/plugins/model-apps/scripts/tests/download-model-app.test.js
index a8d8ee134..9e6ff1122 100644
--- a/plugins/model-apps/scripts/tests/download-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/download-model-app.test.js
@@ -1081,7 +1081,8 @@ test('the global-choice inventory unions the owned sets of every candidate solut
assert.deepStrictEqual((inv.globalChoices || []).map((g) => g.name).sort(), ['set_a', 'set_b']);
assert.deepStrictEqual(looked, ['SolA', 'SolB'], 'the built-in Default container is never looked up');
const unread = await readDescriptionInventory(sdk, 'app-1', new Error('membership unreadable'), new Set(['set_a']));
- assert.deepStrictEqual((unread.incomplete || []).map((i) => i.kind).filter((k) => k !== 'views' && k !== 'charts' && k !== 'forms').sort(), ['businessRules', 'globalChoices']);
+ assert.deepStrictEqual((unread.incomplete || []).map((i) => i.kind).filter((k) => k !== 'views' && k !== 'charts' && k !== 'forms').sort(), ['businessRules', 'fieldSecurityProfiles', 'globalChoices'],
+ 'every class scoped by the solution is unknown, field security profiles included');
assert.strictEqual(unread.globalChoices, undefined, 'nothing is claimed about a scope that could not be read');
});
@@ -2444,11 +2445,200 @@ test('the CLI without --include-managed: a successful download answers, asks, pr
assert.ok(fs.readFileSync(path.join(out, 'pages', SWAP_A, 'page.tsx'), 'utf8').includes('PAGEREF_'), 'the navigating page was rewritten');
assert.ok(fs.existsSync(path.join(out, 'app-spec.json')));
assert.deepStrictEqual(leftovers(out), []);
+ assert.deepStrictEqual(fs.readdirSync(out).filter((n) => n.startsWith('.app-spec.json.')), [], 'no temporary file of the spec is left');
} finally {
fs.rmSync(out, { recursive: true, force: true });
}
});
+// ── app-spec.json is written after pages/ is published: what would refuse its write is refused before pages/ is touched ──────────────
+
+// A temporary sibling writeFileSafe makes for <out>/app-spec.json (`.app-spec.json.<pid>.<8 hex>.tmp`), under either name of <out>:
+// the pre-check's probe is one, and so is the file whose rename gives <out>/app-spec.json its new content.
+const specTemp = (out) => {
+ const outs = new Set([out, fs.realpathSync.native(out)]);
+ return (p) => path.basename(String(p)).startsWith('.app-spec.json.') && outs.has(path.dirname(String(p)));
+};
+
+for (const [what, plant, refusal] of [
+ ['a hard link', (file, elsewhere) => fs.linkSync(file, path.join(elsewhere, 'twin.json')), (e) => e.code === 'UNSAFE_OUTPUT' && e.reason === 'hard-link'],
+ ['read-only', (file) => fs.chmodSync(file, 0o444), (e) => e.code === 'IO_ERROR' && e.reason === 'read-only'],
+ ['a folder', (file) => { fs.rmSync(file); fs.mkdirSync(file); fs.writeFileSync(path.join(file, 'kept.txt'), 'the maker\'s file'); }, (e) => e.code === 'UNSAFE_OUTPUT' && e.reason === 'not-file'],
+ ['a symbolic link', (file, elsewhere) => {
+ const real = path.join(elsewhere, 'real-spec.json');
+ fs.writeFileSync(real, MAKER_SPEC);
+ fs.rmSync(file);
+ fs.symlinkSync(real, file, 'file');
+ }, (e) => e.code === 'UNSAFE_OUTPUT' && e.reason === 'link'],
+ ['in a folder where no new file can be made', (file, elsewhere, t, out) => failFs(t, 'openSync', (p, flags) => flags === 'wx' && specTemp(out)(p), 'EACCES'), (e) => e.code === 'IO_ERROR' && e.reason === 'folder-not-writable'],
+]) {
+ test(`the CLI without --include-managed: an app-spec.json that is ${what} is refused before pages/ is touched: the maker's pages and spec are as they were, and nothing is left`, async (t) => {
+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-cli-spec-refused-'));
+ const elsewhere = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-cli-spec-elsewhere-'));
+ const specFile = path.join(out, 'app-spec.json');
+ try {
+ seedEditedPages(out);
+ fs.writeFileSync(specFile, MAKER_SPEC);
+ try {
+ plant(specFile, elsewhere, t, out);
+ } catch (e) {
+ if (e && e.code === 'EPERM' && what === 'a symbolic link') { t.skip('this account cannot make a symbolic link'); return; }
+ throw e;
+ }
+ const before = treeBytes(out);
+ const res = await cliDownload(t, out);
+ assert.deepStrictEqual(treeBytes(out), before, 'pages/ and app-spec.json are as they were');
+ assert.deepStrictEqual(leftovers(out), [], 'no staging or swap folder is left');
+ assert.deepStrictEqual(fs.readdirSync(out).filter((n) => n.startsWith('.app-spec.json.')), [], 'no temporary file is left');
+ assert.deepStrictEqual(res.emitted.filter((e) => e.ok), [], 'no success emitted');
+ assert.ok(res.thrown && refusal(res.thrown), String(res.thrown && res.thrown.stack));
+ assert.match(res.thrown.message, /^refusing to write .*app-spec\.json: /);
+ assert.ok(res.thrown.message.endsWith(`. The download stopped before replacing anything: ${path.join(out, 'pages')} and ${specFile} are as they were`), res.thrown.message);
+ } finally {
+ // Only the read-only case changed a mode, and only a file's mode needs restoring. A folder planted at the spec's name keeps
+ // its search bit: on POSIX a chmod to 0o666 would drop it, and the clean-up below could not remove the file inside (EACCES).
+ try { if (fs.lstatSync(specFile).isFile()) fs.chmodSync(specFile, 0o666); } catch { /* removed already */ }
+ fs.rmSync(out, { recursive: true, force: true });
+ fs.rmSync(elsewhere, { recursive: true, force: true });
+ }
+ });
+}
+
+// The look at the spec makes, then removes, an empty file of its own. When that file cannot be removed the look does not pass: the
+// download stops before it replaces anything, and the error names the file left, so the maker can delete it.
+for (const lateFailure of [false, true]) {
+ test(`the CLI without --include-managed: an empty file the look at app-spec.json made that cannot be removed stops the download before pages/ is touched, and is named${lateFailure ? ' (a write of the spec that would fail later is never reached)' : ''}`, async (t) => {
+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-cli-spec-probe-'));
+ const specFile = path.join(out, 'app-spec.json');
+ // fs.rmSync loads its recursive remover lazily, and that module keeps the unlink it finds then: load it before unlink is mocked,
+ // or a later clean-up runs the mock.
+ const warmup = path.join(out, 'warmup');
+ fs.mkdirSync(warmup);
+ fs.rmSync(warmup, { recursive: true });
+ try {
+ seedEditedPages(out);
+ fs.writeFileSync(specFile, MAKER_SPEC);
+ const before = treeBytes(out);
+ const opened = [];
+ const open = fs.openSync;
+ t.mock.method(fs, 'openSync', function (p, ...args) {
+ if (specTemp(out)(p)) opened.push(String(p));
+ return open.call(this, p, ...args);
+ });
+ const blocked = failFs(t, 'unlinkSync', (p) => String(p) === opened[0], 'EIO');
+ const renamed = lateFailure ? failFs(t, 'renameSync', specTemp(out), 'EIO') : [];
+ const res = await cliDownload(t, out);
+ const probe = opened[0];
+ assert.ok(probe, 'the look made its file');
+ assert.strictEqual(blocked.length, 1, 'its removal was refused');
+ assert.deepStrictEqual(renamed, [], 'no write of the spec was tried');
+ assert.deepStrictEqual(res.emitted.filter((e) => e.ok), [], 'no success emitted');
+ assert.ok(res.thrown && res.thrown.code === 'IO_ERROR' && res.thrown.reason === 'probe-not-removed', String(res.thrown && res.thrown.stack));
+ assert.ok(res.thrown.message.includes(probe), res.thrown.message);
+ assert.match(res.thrown.message, /an empty file this download made .*can be deleted/);
+ assert.ok(res.thrown.message.endsWith(`. The download stopped before replacing anything: ${path.join(out, 'pages')} and ${specFile} are as they were`), res.thrown.message);
+ assert.deepStrictEqual(leftovers(out), [], 'no staging or swap folder is left');
+ fs.unlinkSync(probe);
+ assert.deepStrictEqual(treeBytes(out), before, 'once the named file is deleted, the folder is exactly as it was');
+ } finally {
+ t.mock.restoreAll();
+ fs.rmSync(out, { recursive: true, force: true });
+ }
+ });
+}
+
+// What the error of a write of the spec that fails after pages/ is published says: what is known (the page tree was published, the
+// write reported an error) and what is not (whether the spec on disk matches the pages), and what to do. Nothing more is claimed.
+const lateSpecSequel = (out) => `. This download had already published its page tree to ${path.join(out, 'pages')} when the write of ${path.join(out, 'app-spec.json')} reported this error, so whether ${path.join(out, 'app-spec.json')} matches those pages has not been confirmed: resolve the error and run the same download again`;
+
+// A write of the spec that fails for a reason no look beforehand can see (a full disk, a lock, a crash) comes after pages/ is published,
+// as it did: the error says what is known, and the same download run again makes the two match.
+for (const hadSpec of [true, false]) {
+ test(`the CLI without --include-managed: a write of app-spec.json that fails after pages/ is published${hadSpec ? '' : ', where there was no app-spec.json'}, says the page tree was published and the spec is not confirmed to match it, and the same download run again makes them match`, async (t) => {
+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-cli-spec-late-'));
+ const specFile = path.join(out, 'app-spec.json');
+ try {
+ seedEditedPages(out);
+ if (hadSpec) fs.writeFileSync(specFile, MAKER_SPEC);
+ const failed = failFs(t, 'renameSync', specTemp(out), 'EIO');
+ const res = await cliDownload(t, out);
+ assert.strictEqual(failed.length, 1, 'the spec\'s rename into place was refused');
+ assert.deepStrictEqual(fs.readdirSync(path.join(out, 'pages')).sort(), [SWAP_A, SWAP_B].sort(), 'pages/ holds this download\'s pages');
+ assert.ok(fs.readFileSync(path.join(out, 'pages', SWAP_A, 'page.tsx'), 'utf8').includes('PAGEREF_'));
+ if (hadSpec) assert.strictEqual(fs.readFileSync(specFile, 'utf8'), MAKER_SPEC, 'app-spec.json is the previous spec');
+ else assert.ok(!fs.existsSync(specFile), 'there is still no app-spec.json');
+ assert.deepStrictEqual(leftovers(out), [], 'no staging or swap folder is left');
+ assert.deepStrictEqual(res.emitted.filter((e) => e.ok), [], 'no success emitted');
+ assert.ok(res.thrown && res.thrown.code === 'IO_ERROR', String(res.thrown && res.thrown.stack));
+ assert.match(res.thrown.message, /^failed to write .*app-spec\.json: EIO: injected/);
+ assert.ok(res.thrown.message.endsWith(lateSpecSequel(out)), res.thrown.message);
+
+ const again = await cliDownload(t, out);
+ assert.strictEqual(again.thrown, null, String(again.thrown && again.thrown.stack));
+ assert.strictEqual(again.emitted.length, 1);
+ assert.strictEqual(again.emitted[0].ok, true, JSON.stringify(again.emitted));
+ const spec = JSON.parse(fs.readFileSync(specFile, 'utf8'));
+ assert.deepStrictEqual(spec.pages.map((p) => p.pageId).sort(), fs.readdirSync(path.join(out, 'pages')).sort(), 'the spec describes the pages in pages/');
+ } finally {
+ fs.rmSync(out, { recursive: true, force: true });
+ }
+ });
+}
+
+// The error claims nothing about what is on disk beyond the published tree, because every claim it once made can be untrue: a spec
+// that already matched the pages (an unchanged app downloaded again), a rename that took effect before it reported an error, and a
+// previous tree that the swap kept because its folder could not be removed.
+for (const [what, arrange, check] of [
+ ['the app is unchanged since the last download, so the spec on disk already describes the pages', async (t, out) => {
+ const first = await cliDownload(t, out);
+ assert.strictEqual(first.thrown, null, String(first.thrown && first.thrown.stack));
+ const before = treeBytes(out);
+ failFs(t, 'renameSync', specTemp(out), 'EIO');
+ return before;
+ }, (out, before) => assert.deepStrictEqual(treeBytes(out), before, 'the spec and the pages are still the matching pair of the first download')],
+ ['the rename of the spec took effect and then reported an error', async (t, out) => {
+ seedEditedPages(out);
+ fs.writeFileSync(path.join(out, 'app-spec.json'), MAKER_SPEC);
+ const rename = fs.renameSync;
+ t.mock.method(fs, 'renameSync', function (from, to) {
+ const done = rename.call(this, from, to);
+ if (specTemp(out)(from)) throw Object.assign(new Error('EIO: injected after the rename'), { code: 'EIO' });
+ return done;
+ });
+ }, (out) => assert.ok(JSON.parse(fs.readFileSync(path.join(out, 'app-spec.json'), 'utf8')).pages.length > 0, 'the new spec is on disk')],
+ ['the swap folder that holds the previous pages could not be removed', async (t, out) => {
+ seedEditedPages(out);
+ fs.writeFileSync(path.join(out, 'app-spec.json'), MAKER_SPEC);
+ const before = treeBytes(path.join(out, 'pages'));
+ const rm = fs.rmSync;
+ t.mock.method(fs, 'rmSync', function (p, ...args) {
+ if (topFolder(out, p, '.pages-replace.') === String(p)) throw Object.assign(new Error('EIO: injected, rm'), { code: 'EIO' });
+ return rm.call(this, p, ...args);
+ });
+ failFs(t, 'renameSync', specTemp(out), 'EIO');
+ return before;
+ }, (out, before) => {
+ const swaps = fs.readdirSync(out).filter((n) => n.startsWith('.pages-replace.'));
+ assert.strictEqual(swaps.length, 1);
+ assert.deepStrictEqual(treeBytes(path.join(out, swaps[0], 'previous')), before, 'the previous pages are kept in the swap folder');
+ }],
+]) {
+ test(`the CLI without --include-managed: the error of a write of app-spec.json that fails after pages/ is published claims nothing it cannot know, when ${what}`, async (t) => {
+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-cli-spec-late-'));
+ try {
+ const before = await arrange(t, out);
+ const res = await cliDownload(t, out);
+ check(out, before);
+ assert.deepStrictEqual(res.emitted.filter((e) => e.ok), [], 'no success emitted');
+ assert.ok(res.thrown && res.thrown.code === 'IO_ERROR', String(res.thrown && res.thrown.stack));
+ assert.ok(res.thrown.message.endsWith(lateSpecSequel(out)), res.thrown.message);
+ for (const untrue of ['not kept', 'still the spec', 'does not describe', 'was not written']) assert.ok(!res.thrown.message.includes(untrue), res.thrown.message);
+ } finally {
+ fs.rmSync(out, { recursive: true, force: true });
+ }
+ });
+}
+
test('writePageTree on Windows: a moment\'s lock on the move into pages/ is waited out, but the move of the maker\'s pages/ aside is one attempt (#814)', (t) => {
freshRenameWaitTotal(t);
const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-win32-'));
@@ -4843,3 +5033,68 @@ test('complete reads use SDK pagination where truncation would change download d
assert.strictEqual(call.opts.top, undefined, `${call.opts.filter} must not cap with top`);
}
});
+
+test('runDownload names a custom field security profile on a secured column in a NOTE and its result, and the spec declares no profile', async () => {
+ // A field security profile is shared security policy and no store proves one is this app's, so a download reports it and declares
+ // none: the secured column round-trips (isSecured), the profile and its permissions and holders stay in the environment untouched.
+ const APP_ID = '6444e0f2-0000-4000-8000-000000000001';
+ const APP_UNIQUE = 'new_fsp';
+ const SM_ID = '6444e0f2-0000-4000-8000-000000000002';
+ const HR = '6444e0f2-0000-4000-8000-0000000000f1';
+ const ADMIN = '572329c1-a042-4e22-be47-367c6374ea45';
+ const SM_XML = '<SiteMap><Area Id="A"><Group Id="G"><SubArea Id="S" Entity="new_order" /></Group></Area></SiteMap>';
+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-fsp-'));
+ const asked = [];
+ const sdk = {
+ fetchArtifact: async () => ({
+ id: APP_ID, name: 'Fsp', uniquename: APP_UNIQUE, description: '',
+ siteMap: { areas: [{ title: 'M', groups: [{ title: 'G', subAreas: [{ type: 'Entity', entity: 'new_order' }] }] }] },
+ }),
+ queryRecords: async (logical, opts) => {
+ const filter = (opts && opts.filter) || '';
+ if (logical === 'appmodule') return [{ appmoduleid: APP_ID, appmoduleidunique: APP_ID, uniquename: APP_UNIQUE }];
+ if (logical === 'appmodulecomponent') return /componenttype eq 62/.test(filter) ? [{ objectid: SM_ID, componenttype: 62 }] : [];
+ if (logical === 'sitemap') return [{ sitemapxml: SM_XML }];
+ if (logical === 'fieldpermission') {
+ asked.push({ logical, ...opts });
+ return /entityname eq 'new_order'/.test(filter) && /attributelogicalname eq 'new_salary'/.test(filter)
+ ? [{ _fieldsecurityprofileid_value: ADMIN }, { _fieldsecurityprofileid_value: HR }] : [];
+ }
+ if (logical === 'fieldsecurityprofile') {
+ asked.push({ logical, ...opts });
+ return [{ fieldsecurityprofileid: HR, name: 'HR' }].filter((p) => filter.includes(p.fieldsecurityprofileid));
+ }
+ return [];
+ },
+ fetchEntityMetadata: async (logical) => ({
+ logicalName: logical, schemaName: 'new_order', displayName: 'Order', primaryNameAttribute: 'new_name',
+ attributes: [
+ { logicalName: 'new_name', displayName: 'Name', attributeType: 'String', isCustomAttribute: true },
+ { logicalName: 'new_salary', displayName: 'Salary', attributeType: 'String', isCustomAttribute: true, isSecured: true },
+ ],
+ relationships: [],
+ }),
+ dataverse: { get: async () => ({ status: 404, headers: {}, body: {} }) },
+ };
+ const origWrite = process.stderr.write.bind(process.stderr);
+ const written = [];
+ process.stderr.write = (chunk, ...rest) => { written.push(String(chunk)); return origWrite(chunk, ...rest); };
+ let res;
+ try {
+ res = await runDownload({ sdk: currentReadSdk(sdk, { appId: APP_ID, layerId: APP_ID, sitemapXml: SM_XML }), genpage: fakeGenpage(), outDir: out, appId: APP_ID, appUnique: APP_UNIQUE });
+ } finally {
+ process.stderr.write = origWrite;
+ fs.rmSync(out, { recursive: true, force: true });
+ }
+ assert.strictEqual(res.ok, true, res.error);
+ const note = written.join('').split('\n').find((l) => /field security profile/.test(l)) || '';
+ assert.match(note, /^NOTE: 1 field security profile \(HR\) is not declared in fieldSecurityProfiles\[\]: .*a rebuild neither changes nor recreates it/);
+ assert.doesNotMatch(written.join(''), /System Administrator/);
+ assert.deepStrictEqual(res.fieldSecurityProfiles, { omitted: [{ kind: 'fieldSecurityProfile', id: HR, name: 'HR', code: 'ownership-unproven', reason: 'no binding store record proves this app authored it, so it is not declared' }] });
+ // The spec: the column stays secured; no profile, permission or holder; and the inventory key stays out of descriptionInventory.
+ assert.strictEqual(res.spec.entities[0].columns.find((c) => c.schemaName === 'new_salary').isSecured, true);
+ assert.ok(!('fieldSecurityProfiles' in res.spec));
+ assert.ok(!res.spec.descriptionInventory || !('fieldSecurityProfiles' in res.spec.descriptionInventory));
+ assert.doesNotMatch(JSON.stringify(res.spec), new RegExp(`${HR}|${ADMIN}`));
+ assert.deepStrictEqual(asked.map((q) => [q.logical, q.select]), [['fieldpermission', ['_fieldsecurityprofileid_value']], ['fieldsecurityprofile', ['fieldsecurityprofileid', 'name']]]);
+});
diff --git a/plugins/model-apps/scripts/tests/download-not-round-tripped.test.js b/plugins/model-apps/scripts/tests/download-not-round-tripped.test.js
index 11c4e9a12..c368cfb33 100644
--- a/plugins/model-apps/scripts/tests/download-not-round-tripped.test.js
+++ b/plugins/model-apps/scripts/tests/download-not-round-tripped.test.js
@@ -332,4 +332,136 @@ test('a failed command read is reported as UNKNOWN, not as an app with no comman
await readDescriptionInventory(sdk, APP, null, new Set(), NO_LAYER, opts);
assert.deepStrictEqual(sdk.queries.filter((q) => q.set === 'appaction'), [], JSON.stringify(opts));
}
+});
+// --- the managed download's report seam (lib/managed-restore-report.js) ---------------------------------------------------------
+const { subtractRestored, omission, REASONS } = require('../lib/managed-restore-report.js');
+
+test('subtractRestored drops the restored rows by normalized id only, drops a class it empties, and leaves everything else as it was', () => {
+ const V1 = '0a0a0a0a-0000-4000-8000-000000000001';
+ const V2 = '0a0a0a0a-0000-4000-8000-000000000002';
+ const C1 = '0c0c0c0c-0000-4000-8000-000000000001';
+ // Two views share a name; only the id restored goes.
+ const inv = inventory({ views: [{ id: V1, name: 'Active', entity: 'contoso_project' }, { id: V2, name: 'Active', entity: 'contoso_project' }], charts: [{ id: C1, name: 'By Status', entity: 'contoso_project' }] });
+ const frozen = JSON.stringify(inv);
+ const out = subtractRestored(inv, { views: [`{${V2.toUpperCase()}}`], charts: [C1] });
+ assert.deepStrictEqual(out.views, [{ id: V1, name: 'Active', entity: 'contoso_project' }]);
+ assert.strictEqual('charts' in out, false, 'an emptied class loses its key, as "the read found none" would otherwise read');
+ assert.deepStrictEqual(out.forms, inv.forms);
+ assert.strictEqual(JSON.stringify(inv), frozen, 'the inventory handed in is not changed');
+ assert.strictEqual(notRoundTrippedSummary(out).total, 3);
+ // Nothing restored, or a name instead of an id: the very same inventory.
+ for (const restored of [{}, { views: [] }, { views: ['Active'] }, undefined]) assert.strictEqual(subtractRestored(inv, restored), inv, JSON.stringify(restored));
+});
+
+test('omission carries safe identity and the fixed reason of its code, never text a service gave', () => {
+ const o = omission({ kind: 'view', id: '{0A0A0A0A-0000-4000-8000-000000000001}', key: 'contoso_item/Active', name: 'Active', code: 'changed', fields: ['layout', 'x\u0000y'] });
+ assert.deepStrictEqual(o, { kind: 'view', id: '0a0a0a0a-0000-4000-8000-000000000001', key: 'contoso_item/Active', name: 'Active', fields: ['layout'], code: 'changed', reason: REASONS.changed });
+ assert.deepStrictEqual(omission({ kind: 'chart', id: 'not a guid', name: 'a\nb', code: 'unread' }), { kind: 'chart', code: 'unread', reason: REASONS.unread }, 'an id that is not a GUID and a name with a line break are left out');
+ assert.throws(() => omission({ kind: 'view', code: 'HTTP 500: <fetch>secret</fetch>' }), /unknown omission code/);
+});
+
+// --- field security profiles: reported, never declared -------------------------------------------------------------------------
+// A profile is shared security policy and no binding store family proves one is this app's, so the download names the custom profiles
+// it finds (in the app's solution, or holding a permission on a column the download secures) and declares none of them.
+const { fieldSecurityProfileOmissions, fieldSecurityProfilesNote } = require('../download-model-app.js');
+const SOL_ID = '50505050-0000-4000-8000-000000000001';
+const ADMIN = '572329c1-a042-4e22-be47-367c6374ea45';
+const P_HR = '70707070-0000-4000-8000-000000000001';
+const P_PAY = '70707070-0000-4000-8000-000000000002';
+const P_FAKE_ADMIN = '70707070-0000-4000-8000-000000000003';
+const P_OTHER = '70707070-0000-4000-8000-000000000004';
+function profileSdk({ components = [], permissions = [], profiles = [], fail = {} } = {}) {
+ const queries = [];
+ return {
+ queries,
+ dataverse: { get: async () => { throw new Error('no metadata read is expected'); } },
+ queryRecords: async (set, opts) => {
+ queries.push({ set, ...opts });
+ if (fail[set]) throw new Error(fail[set]);
+ if (set === 'solution') return [{ solutionid: SOL_ID }];
+ if (set === 'solutioncomponent') return /componenttype eq 70\b/.test(opts.filter) ? components.map((id) => ({ objectid: id })) : [];
+ if (set === 'fieldpermission') {
+ // `entityname eq '<table>' and (attributelogicalname eq '<column>' or …)`
+ const table = (/entityname eq '([^']+)'/.exec(opts.filter) || [])[1];
+ const columns = [...String(opts.filter).matchAll(/attributelogicalname eq '([^']+)'/g)].map((m) => m[1]);
+ return permissions.filter((p) => p.table === table && columns.includes(p.column)).map((p) => ({ fieldpermissionid: `fp-${p.profile}-${p.column}`, _fieldsecurityprofileid_value: p.profile }));
+ }
+ if (set === 'fieldsecurityprofile') {
+ const ids = [...String(opts.filter).matchAll(/fieldsecurityprofileid eq ([0-9a-f-]{36})/gi)].map((m) => m[1].toLowerCase());
+ return profiles.filter((p) => ids.includes(p.fieldsecurityprofileid));
+ }
+ return [];
+ },
+ };
+}
+const SECURED = [{ table: 'contoso_staff', column: 'contoso_salary' }, { table: 'contoso_staff', column: 'contoso_bonus' }];
+const PROFILES = [
+ { fieldsecurityprofileid: ADMIN, name: 'System Administrator' },
+ { fieldsecurityprofileid: P_HR, name: 'HR' },
+ { fieldsecurityprofileid: P_PAY, name: 'Payroll' },
+ { fieldsecurityprofileid: P_FAKE_ADMIN, name: 'System Administrator' },
+ { fieldsecurityprofileid: P_OTHER, name: 'Elsewhere' },
+];
+
+test('the download names the custom field security profiles it finds by the app\u2019s solution or its secured columns, once each, and never System Administrator', async () => {
+ const sdk = profileSdk({
+ components: [P_HR],
+ permissions: [
+ { table: 'contoso_staff', column: 'contoso_salary', profile: ADMIN },
+ { table: 'contoso_staff', column: 'contoso_salary', profile: P_HR },
+ { table: 'contoso_staff', column: 'contoso_bonus', profile: P_PAY },
+ { table: 'contoso_staff', column: 'contoso_bonus', profile: P_FAKE_ADMIN },
+ { table: 'contoso_staff', column: 'contoso_notes', profile: P_OTHER },
+ ],
+ profiles: PROFILES,
+ });
+ const inv = await readDescriptionInventory(sdk, APP, 'ContosoStaff', new Set(), NO_LAYER, { securedColumns: SECURED });
+ assert.deepStrictEqual(inv.fieldSecurityProfiles, [{ id: P_HR, name: 'HR' }, { id: P_PAY, name: 'Payroll' }]);
+ assert.ok(!(inv.incomplete || []).some((i) => i.kind === 'fieldSecurityProfiles'));
+ // Read: the profile ids a permission names and each profile's id and name. Never a permission's bits, nor who a profile is given to.
+ const perms = sdk.queries.filter((q) => q.set === 'fieldpermission');
+ assert.strictEqual(perms.length, 1, 'one request for the table');
+ assert.deepStrictEqual(perms[0].select, ['_fieldsecurityprofileid_value']);
+ assert.strictEqual(perms[0].filter, "entityname eq 'contoso_staff' and (attributelogicalname eq 'contoso_bonus' or attributelogicalname eq 'contoso_salary')");
+ assert.strictEqual(perms[0].paginate, true);
+ const names = sdk.queries.filter((q) => q.set === 'fieldsecurityprofile');
+ assert.deepStrictEqual(names.map((q) => q.select), [['fieldsecurityprofileid', 'name']]);
+ assert.doesNotMatch(names[0].filter, new RegExp(ADMIN), 'System Administrator is dropped by its id before any read');
+ assert.ok(sdk.queries.every((q) => !/systemuser|team|canread|cancreate|canupdate/i.test(`${q.set} ${q.select} ${q.filter}`)));
+
+ // Reported as omissions with the fixed reason: id and name only.
+ const omitted = fieldSecurityProfileOmissions(inv);
+ assert.deepStrictEqual(omitted, [
+ { kind: 'fieldSecurityProfile', id: P_HR, name: 'HR', code: 'ownership-unproven', reason: REASONS['ownership-unproven'] },
+ { kind: 'fieldSecurityProfile', id: P_PAY, name: 'Payroll', code: 'ownership-unproven', reason: REASONS['ownership-unproven'] },
+ ]);
+ const note = fieldSecurityProfilesNote(omitted);
+ assert.match(note, /^NOTE: 2 field security profiles \(HR, Payroll\) are not declared in fieldSecurityProfiles\[\]/);
+ assert.ok(note.endsWith('\n') && !note.includes('System Administrator'));
+ assert.strictEqual(fieldSecurityProfilesNote([]), '');
+ assert.deepStrictEqual(fieldSecurityProfileOmissions({}), []);
+ // The class is not a not-round-tripped artifact class (it is not in descriptionInventory), so the report is unchanged by it.
+ assert.deepStrictEqual(notRoundTrippedSummary({ fieldSecurityProfiles: inv.fieldSecurityProfiles }), null);
+});
+
+test('a field security profile read that fails is reported as UNKNOWN, keeping what was found; with nothing to look in, nothing is read', async () => {
+ const unknown = (inv) => (inv.incomplete || []).filter((i) => i.kind === 'fieldSecurityProfiles');
+ const permsFail = await readDescriptionInventory(profileSdk({ components: [P_HR], profiles: PROFILES, fail: { fieldpermission: 'HTTP 403 secret detail' } }), APP, 'ContosoStaff', new Set(), NO_LAYER, { securedColumns: SECURED });
+ assert.deepStrictEqual(permsFail.fieldSecurityProfiles, [{ id: P_HR, name: 'HR' }]);
+ assert.strictEqual(unknown(permsFail).length, 1);
+ assert.doesNotMatch(unknown(permsFail)[0].reason, /secret detail/, 'a fixed reason, not the service\u2019s words');
+ assert.match(notRoundTrippedWarning(notRoundTrippedSummary(permsFail)), /fieldSecurityProfiles — /);
+
+ const namesFail = await readDescriptionInventory(profileSdk({ components: [P_HR], fail: { fieldsecurityprofile: 'HTTP 500' } }), APP, 'ContosoStaff', new Set(), NO_LAYER, { securedColumns: SECURED });
+ assert.strictEqual(namesFail.fieldSecurityProfiles, undefined);
+ assert.strictEqual(unknown(namesFail).length, 1);
+
+ const solutionUnread = await readDescriptionInventory(profileSdk({ profiles: PROFILES }), APP, new Error('the solutions could not be read'), new Set(), NO_LAYER, { securedColumns: [] });
+ assert.strictEqual(unknown(solutionUnread).length, 1, 'the solution\u2019s profiles are unknown, not none');
+
+ const nothing = profileSdk({ components: [P_HR], profiles: PROFILES });
+ const none = await readDescriptionInventory(nothing, APP, null, new Set(), NO_LAYER, {});
+ assert.strictEqual(none.fieldSecurityProfiles, undefined);
+ assert.deepStrictEqual(unknown(none), []);
+ assert.deepStrictEqual(nothing.queries.filter((q) => /^field/.test(q.set)), [], 'no solution and no secured column: no profile read');
});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/download-order.test.js b/plugins/model-apps/scripts/tests/download-order.test.js
index 6a85cff62..ad8d2d01e 100644
--- a/plugins/model-apps/scripts/tests/download-order.test.js
+++ b/plugins/model-apps/scripts/tests/download-order.test.js
@@ -14,8 +14,9 @@ const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const {
- runDownload, parseDownloadedPages, assignPageKeys, readDescriptionInventory, notRoundTrippedSummary, compareText,
+ runDownload, parseDownloadedPages, assignPageKeys, readDescriptionInventory, notRoundTrippedSummary, notRoundTrippedReport, notRoundTrippedWarning, compareText,
} = require('../download-model-app.js');
+const { subtractRestored } = require('../lib/managed-restore-report.js');
const { currentReadSdk } = require('./helpers/app-membership-sdk.js');
const { fakeGenpage } = require('./helpers/fake-genpage.js');
@@ -152,14 +153,14 @@ function withDirectoryOrder(listing, fn) {
}
// Everything a download hands back or writes, as data.
-async function download(order, listing = identity) {
+async function download(order, listing = identity, options = {}) {
const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-order-'));
const stderr = [];
const realWrite = process.stderr.write;
try {
process.stderr.write = (chunk) => { stderr.push(String(chunk)); return true; };
const genpage = fakeGenpage({ pages: order(PAGES.map((p) => ({ ...p, source: `export default function Page() { return '${p.pageId}'; }\n` }))) });
- const res = await withDirectoryOrder(listing, () => runDownload({ sdk: server(order), genpage, outDir: out, appId: APP_ID, appUnique: APP_UNIQUE }));
+ const res = await withDirectoryOrder(listing, () => runDownload({ sdk: server(order), genpage, outDir: out, appId: APP_ID, appUnique: APP_UNIQUE, ...options }));
assert.ok(res.ok, JSON.stringify(res));
const tree = {};
const walk = (dir) => { for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { const full = path.join(dir, entry.name); if (entry.isDirectory()) walk(full); else tree[path.relative(out, full).replace(/\\/g, '/')] = fs.readFileSync(full, 'utf8'); } };
@@ -255,6 +256,27 @@ test('the same members, only ordered: nothing a download wrote is dropped or add
assert.strictEqual(res.notRoundTripped.total, FORMS.length + VIEWS.length + CHARTS.length + RULES.length + 3);
});
+// The managed download (main, --include-managed) asks runDownload to defer its not-round-tripped report, so the report can be
+// printed once the restore has put some of it back into the spec. Deferred, the download prints nothing else differently, answers the
+// same report, and hands back the parts main recomputes it from; not asked, it is what it always was.
+test('deferReport: the report is not printed but handed back as the parts it is computed from; everything else is the same download', async () => {
+ const plain = await download(identity);
+ const deferred = await download(identity, identity, { deferReport: true });
+ const warning = notRoundTrippedWarning(plain.res.notRoundTripped);
+ assert.ok(warning && plain.stderr.includes(warning), 'the plain download prints the report');
+ assert.strictEqual(deferred.stderr, plain.stderr.replace(warning, ''), 'deferred, only the report is missing from what the download says');
+ assert.deepStrictEqual(deferred.res.notRoundTripped, plain.res.notRoundTripped);
+ assert.deepStrictEqual(deferred.tree, plain.tree);
+ assert.strictEqual(JSON.stringify(deferred.res.spec), JSON.stringify(plain.res.spec));
+ assert.strictEqual('deferredReport' in plain.res, false, 'a caller that does not ask gets no new field');
+ const { inventory, membershipNotes } = deferred.res.deferredReport;
+ assert.deepStrictEqual(notRoundTrippedReport(inventory, deferred.res.spec, membershipNotes), plain.res.notRoundTripped, 'the parts give the report back');
+ // Less a restored view, by id: one view fewer, and nothing else. A view sharing its name on another table stays.
+ const restored = notRoundTrippedReport(subtractRestored(inventory, { views: [`{${g('44444444', 2).toUpperCase()}}`] }), deferred.res.spec, membershipNotes);
+ assert.strictEqual(restored.total, plain.res.notRoundTripped.total - 1);
+ assert.deepStrictEqual(restored.entities.find((e) => e.entity === 'contoso_item').views, ['My Items']);
+});
+
test('what is not reordered: the navigation keeps the sitemap\'s order, and every page folder holds its own page', async () => {
const { res, tree } = await download(reversed, reversed);
// `appShell` is the app's own navigation, in the order its sitemap lists it — not the pages' order in `pages[]`.
diff --git a/plugins/model-apps/scripts/tests/download-portable-detail-real-bundle.test.js b/plugins/model-apps/scripts/tests/download-portable-detail-real-bundle.test.js
index 7b584ea5b..145d70494 100644
--- a/plugins/model-apps/scripts/tests/download-portable-detail-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/download-portable-detail-real-bundle.test.js
@@ -14,7 +14,9 @@ const { validateAppSpec } = require('../lib/app-spec.js');
// Component type 62 is Site Map:
// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/appmodulecomponent
// The command-bar inventory adds two: the `appaction` entity-set lookup and one `appactions` read for up to 20 of the app's tables.
-const DOWNLOAD_READS = 85;
+// The field security profile report adds one: the app solution's type-70 (Field Security Profile) components. This app secures no
+// column, so it sends no `fieldpermission` read, and the solution holds no profile, so no `fieldsecurityprofiles` read either.
+const DOWNLOAD_READS = 86;
const reason = { label: 'Review', state: 'Active', value: 100000042, color: '#336699' };
const key = { schemaName: 'contoso_emailkey', displayName: 'Email Key', columns: ['contoso_email'] };
diff --git a/plugins/model-apps/scripts/tests/genpage-edit-contract.test.js b/plugins/model-apps/scripts/tests/genpage-edit-contract.test.js
index 277832c9c..302ffb524 100644
--- a/plugins/model-apps/scripts/tests/genpage-edit-contract.test.js
+++ b/plugins/model-apps/scripts/tests/genpage-edit-contract.test.js
@@ -110,3 +110,71 @@ test('apply phase limits mutations to the verified Requested Changes section', (
assert.match(phase5, /only[\s\S]{0,120}## Requested Changes/i);
assert.match(flow.split('## Edit Phase 4: Plan the Edit')[1]?.split('## Edit Phase 5:')[0] || '', /page[\s\S]{0,120}change list/i);
});
+
+// Pull-to-repo and promotion (#675). Pulling pages into the project is a read of the environment and a local write, so
+// the section must name no command that changes the environment, and an unattended pull must neither guess a page nor
+// replace a local copy. The promotion guide is loaded only for a promote request and cites Microsoft Learn for its rules.
+const readText = (...parts) => fs.readFileSync(path.join(PLUGIN, ...parts), 'utf8').replace(/\r\n/g, '\n');
+const pullSection = () => {
+ const skill = readText('skills', 'genpage', 'SKILL.md');
+ const at = skill.indexOf('\n## Pulling existing pages into the project\n');
+ assert.ok(at >= 0, 'SKILL.md has the pull section');
+ const rest = skill.slice(at + 1);
+ const next = rest.indexOf('\n## ', 3);
+ return next < 0 ? rest : rest.slice(0, next);
+};
+
+test('pulling pages into the project reads the environment and never writes to it', () => {
+ const pull = pullSection();
+ const scripts = [...pull.matchAll(/scripts\/([\w-]+\.js)"(?: (\w+))?/g)].map((m) => `${m[1]} ${m[2] || ''}`.trim());
+ assert.deepEqual([...new Set(scripts)].sort(), [
+ 'apps.js list', 'check-auth.js', 'genpage-base.js record', 'genpage.js download', 'genpage.js list',
+ ]);
+ assert.doesNotMatch(pull, /genpage-upload|add-to-app|remove-from-app|genpage\.js" delete|--overwrite-deployed/);
+ assert.match(pull, /`<project-root>\/<page-id>\/`/);
+ assert.match(pull, /--page-id '<page-id1>,<page-id2>' --output-directory '<project-root>'/);
+ assert.match(pull.replace(/\s+/g, ' '), /on `ok: false` show the `message` verbatim and stop/, 'a failed sign-in check stops the pull');
+});
+
+test('an unattended pull neither guesses a page nor replaces a local copy', () => {
+ const pull = pullSection().replace(/\s+/g, ' ');
+ assert.match(pull, /\*\*Unattended:\*\* pull only the pages `\$ARGUMENTS` names by id or exact name; when none is named, or a name matches more than one page, halt/);
+ assert.match(pull, /\*\*Unattended:\*\* skip it and report it\. A pull never replaces local work nobody agreed to replace\./);
+ assert.match(pull, /Do not edit, build or upload the pulled pages in this request\./);
+});
+
+test('the promotion guide is read only for a promote request and cites Microsoft Learn for each rule', () => {
+ const skill = readText('skills', 'genpage', 'SKILL.md');
+ const loads = skill.split('\n').filter((line) => line.includes('promotion.md'));
+ assert.equal(loads.length, 2);
+ for (const line of loads) assert.match(line, /promot|\[promotion\.md\]/i);
+ assert.match(skill.replace(/\s+/g, ' '), /\*\*Promote pages to another environment\*\*[^.]*: read \[promotion\.md\]\(\.\.\/\.\.\/references\/promotion\.md\) and follow it\. Read it only for such a request\./);
+
+ const guide = readText('references', 'promotion.md');
+ const sections = guide.split(/\n(?=## \d+\. )/).slice(1);
+ assert.equal(sections.length, 10);
+ const titles = sections.map((s) => s.split('\n')[0]);
+ for (const s of sections.slice(0, 9)) {
+ assert.match(s, /\(https:\/\/learn\.microsoft\.com\/[^)\s]+\)/, `${s.split('\n')[0]} cites Microsoft Learn`);
+ }
+ assert.deepEqual(titles.map((t) => t.replace(/^## \d+\. /, '')), [
+ 'Package the pages first', 'Managed or unmanaged', 'Full solution or patch', 'Version number', 'Dependency check',
+ 'Import order', 'Connections and the import', 'Rollback', 'What travels with a page, and what does not', 'Record the promotion',
+ ]);
+ assert.match(guide, /The full authoring conversation: in the target, the designer shows only the first prompt and the published code/);
+ // Learn qualifies both promises: a managed component may be customized in the target through an unmanaged layer when its
+ // managed properties allow it, and an upgrade deletes the components a new version drops, with their data, which no
+ // roll-forward brings back. So neither may be stated as absolute, and the backup advice covers such an upgrade too.
+ const flat = (title) => (sections.find((s) => s.startsWith(title)) || '').replace(/\s+/g, ' ');
+ const managed = flat('## 2. Managed or unmanaged');
+ assert.doesNotMatch(managed, /its components cannot be edited in the target/);
+ assert.match(managed, /cannot be edited in the target directly\. A component it brings can still be customized there when its managed properties allow it/);
+ const rollback = flat('## 8. Rollback');
+ assert.doesNotMatch(rollback, /loses nothing/);
+ assert.match(rollback, /it does not bring back data an earlier upgrade or migration deleted/);
+ assert.match(rollback, /Back up the target before an import that cannot be undone:\*\* any unmanaged import, and any upgrade that removes components/);
+ // Guidance, not automation: the guide exports nothing and changes no page; the one write it runs is the documented import.
+ assert.doesNotMatch(guide, /genpage-upload\.js|pac solution export|ExportSolution/);
+ const writes = [...guide.matchAll(/scripts\/([\w-]+\.js)"(?: (\w+))?/g)].map((m) => `${m[1]} ${m[2] || ''}`.trim());
+ assert.deepEqual([...new Set(writes)].sort(), ['genpage.js types', 'list-custom-apis.js', 'list-tables.js', 'solution-settings.js import', 'solution-settings.js template']);
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/golden/lifecycle-trail.build.txt b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.build.txt
index 9a4342caa..e6537efe5 100644
--- a/plugins/model-apps/scripts/tests/golden/lifecycle-trail.build.txt
+++ b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.build.txt
@@ -310,7 +310,7 @@
1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_task' and name eq 'My Open Tasks'&$top=1 -> 200
1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_task' and name eq 'Open Tasks'&$top=1 -> 200
1x GET /savedqueryvisualizations?$select=primaryentitytypecode&$filter=savedqueryvisualizationid eq <id>&$top=1 -> 200
- 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_project' and name eq 'Projects by Priority'&$top=1 -> 200
+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid,primaryentitytypecode,name,description,datadescription,presentationdescription&$filter=primaryentitytypecode eq 'contoso_project' and name eq 'Projects by Priority'&$top=2 -> 200
1x GET /sitemaps?$select=sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200
1x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber -> 200
2x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formxml -> 200
diff --git a/plugins/model-apps/scripts/tests/golden/lifecycle-trail.download.txt b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.download.txt
index 12f65c8d8..7348bab92 100644
--- a/plugins/model-apps/scripts/tests/golden/lifecycle-trail.download.txt
+++ b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.download.txt
@@ -1,4 +1,4 @@
-# 136 requests, 0 publishes
+# 137 requests, 0 publishes
## after the last publish
4x GET /EntityDefinitions(<id>)?$select=LogicalName,IsCustomEntity -> 200
1x GET /EntityDefinitions(LogicalName='appaction')?$select=EntitySetName -> 200
@@ -105,6 +105,7 @@
1x GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapname,sitemapnameunique,sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200
1x GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapxml,componentstate&$filter=sitemapid eq <id> -> 200
1x GET /solutioncomponents?$select=_solutionid_value&$filter=objectid eq <id> -> 200
+ 1x GET /solutioncomponents?$select=objectid&$filter=_solutionid_value eq <id> and componenttype eq 70 -> 200
1x GET /solutioncomponents?$select=objectid&$filter=_solutionid_value eq <id> and componenttype eq 9 -> 200
1x GET /solutioncomponents?$select=objectid,componenttype&$filter=_solutionid_value eq <id> and componenttype eq 29 -> 200
1x GET /solutions?$select=solutionid&$filter=uniquename eq 'ContosoKitchen'&$top=1 -> 200
diff --git a/plugins/model-apps/scripts/tests/golden/lifecycle-trail.edit.txt b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.edit.txt
index f5606cbdd..6fdae7c01 100644
--- a/plugins/model-apps/scripts/tests/golden/lifecycle-trail.edit.txt
+++ b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.edit.txt
@@ -243,7 +243,7 @@
1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_task' and name eq 'My Open Tasks'&$top=1 -> 200
1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_task' and name eq 'Open Tasks'&$top=1 -> 200
1x GET /savedqueryvisualizations?$select=primaryentitytypecode&$filter=savedqueryvisualizationid eq <id>&$top=1 -> 200
- 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_project' and name eq 'Projects by Priority'&$top=1 -> 200
+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid,primaryentitytypecode,name,description,datadescription,presentationdescription&$filter=primaryentitytypecode eq 'contoso_project' and name eq 'Projects by Priority'&$top=2 -> 200
1x GET /sitemaps?$select=sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200
1x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber -> 200
2x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formxml -> 200
diff --git a/plugins/model-apps/scripts/tests/golden/lifecycle-trail.rebuild.txt b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.rebuild.txt
index 82cc3fae7..1ce5c39f9 100644
--- a/plugins/model-apps/scripts/tests/golden/lifecycle-trail.rebuild.txt
+++ b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.rebuild.txt
@@ -195,7 +195,7 @@
1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_task' and name eq 'My Open Tasks'&$top=1 -> 200
1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_task' and name eq 'Open Tasks'&$top=1 -> 200
1x GET /savedqueryvisualizations?$select=primaryentitytypecode&$filter=savedqueryvisualizationid eq <id>&$top=1 -> 200
- 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_project' and name eq 'Projects by Priority'&$top=1 -> 200
+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid,primaryentitytypecode,name,description,datadescription,presentationdescription&$filter=primaryentitytypecode eq 'contoso_project' and name eq 'Projects by Priority'&$top=2 -> 200
1x GET /sitemaps?$select=sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200
1x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber -> 200
2x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formxml -> 200
diff --git a/plugins/model-apps/scripts/tests/golden/lifecycle-trail.verify.txt b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.verify.txt
index 58f617cad..59be0e3b9 100644
--- a/plugins/model-apps/scripts/tests/golden/lifecycle-trail.verify.txt
+++ b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.verify.txt
@@ -49,7 +49,7 @@
1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_task' and name eq 'My Open Tasks'&$top=1 -> 200
1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_task' and name eq 'Open Tasks'&$top=1 -> 200
1x GET /savedqueryvisualizations?$select=primaryentitytypecode&$filter=savedqueryvisualizationid eq <id>&$top=1 -> 200
- 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_project' and name eq 'Projects by Priority'&$top=1 -> 200
+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid,primaryentitytypecode,name,description,datadescription,presentationdescription&$filter=primaryentitytypecode eq 'contoso_project' and name eq 'Projects by Priority'&$top=2 -> 200
1x GET /sitemaps?$select=sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200
1x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber -> 200
2x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formxml -> 200
diff --git a/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-org.js b/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-org.js
index 3a7dec35f..a22f32b08 100644
--- a/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-org.js
+++ b/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-org.js
@@ -27,6 +27,9 @@
// pages the generative pages (`uxagentprojects`, their files and conversation), held by the stateful page fake the SDK's own
// tests drive (helpers/fake-genpage-server.js), which takes their writes, a file's bytes and a `PublishXml`; their reads
// are answered here from its state, so every query option a read carries is applied (pageRows, answerPageRead).
+// configuration only in an org made with `{ configuration: true }`: environment variable definitions and values, connection
+// references and Custom APIs with their parameters and properties (CONFIGURATION_TABLES), each created as a deep insert
+// may send it and read back with the `$expand` of its child collection.
//
// The platform rules it keeps, and where each comes from. MEASURED or DOCUMENTED (the plugin's code or another fake records it):
// - a read BY ID answers the saved row with its current token (the SDK reads a form it just created that way), except an app module,
@@ -108,6 +111,39 @@ const SYSTEM_TABLES = {
account: { set: 'accounts', id: 'accountid', name: 'name', otc: 1, stock: true },
contact: { set: 'contacts', id: 'contactid', name: 'fullname', otc: 2, stock: true },
};
+// Column security, modelled only for an org made with `{ fieldSecurity: true }` (a test that seeds profiles): a field security profile,
+// its column permissions, and — as N:N links in `associations` — the users and teams it is given to (systemuserprofiles_association,
+// teamprofiles_association). Their READS follow the read contract below; nothing writes them here, so any write to them is answered
+// 501 and recorded in `unexpected`, as every unmodelled request is. Without the option they are not tables of the org at all.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/fieldsecurityprofile
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/fieldpermission
+const FIELD_SECURITY_TABLES = {
+ fieldsecurityprofile: { set: 'fieldsecurityprofiles', id: 'fieldsecurityprofileid', name: 'name', otc: 9020, componentType: 70 },
+ fieldpermission: { set: 'fieldpermissions', id: 'fieldpermissionid', name: null, otc: 9019 },
+};
+// Protected configuration, modelled only for an org made with `{ configuration: true }` (a test that builds and downloads it): environment
+// variable definitions and their values, connection references, and Custom APIs with their request parameters and response properties
+// (and the definitions, not the rows, of the duplicate rule tables).
+// A definition, a reference and a Custom API created with the solution header join that solution (an environment variable definition
+// as type 380, the other two as their table's ObjectTypeCode, which is what a current environment lists them under); a value never
+// joins one, and a Custom API's parameters and properties created inside it do not either — the build adds each with
+// AddSolutionComponent (helpers/fake-config-org.js keeps the same rules, and says where each comes from). A Custom API's children
+// arrive in its create as a deep insert, and a read may `$expand` a definition's values or a Custom API's children.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/environmentvariabledefinition
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/connectionreference
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/custom-api-tables
+const CONFIGURATION_TABLES = {
+ environmentvariabledefinition: { set: 'environmentvariabledefinitions', id: 'environmentvariabledefinitionid', name: 'schemaname', otc: 380, componentType: 380 },
+ environmentvariablevalue: { set: 'environmentvariablevalues', id: 'environmentvariablevalueid', name: null, otc: 381 },
+ connectionreference: { set: 'connectionreferences', id: 'connectionreferenceid', name: 'connectionreferencelogicalname', otc: 10132, componentType: 10132 },
+ customapi: { set: 'customapis', id: 'customapiid', name: 'uniquename', otc: 10133, componentType: 10133 },
+ customapirequestparameter: { set: 'customapirequestparameters', id: 'customapirequestparameterid', name: 'uniquename', otc: 10134 },
+ customapiresponseproperty: { set: 'customapiresponseproperties', id: 'customapiresponsepropertyid', name: 'uniquename', otc: 10135 },
+ // Definitions only: the build reads the ObjectTypeCode of every table protected configuration may add to a solution, duplicate rules
+ // included, before its first write. No test of this org declares a duplicate rule, so their rows are not modelled.
+ duplicaterule: { set: 'duplicaterules', id: 'duplicateruleid', name: 'name', otc: 4414 },
+ duplicaterulecondition: { set: 'duplicateruleconditions', id: 'duplicateruleconditionid', name: null, otc: 4416 },
+};
const PAGE_PATH = /^\/(uxagentprojects|uxagentprojectfiles|agentconversationmessages)\b/;
// THE READ CONTRACT of the record half: the columns a read may name, per system table, EXPLICITLY — `fields` the platform always fills
@@ -143,6 +179,33 @@ const RECORD_SCHEMA = {
settingdefinition: { fields: ['settingdefinitionid', 'uniquename', 'displayname', 'datatype', 'defaultvalue', 'isoverridable', 'overridablelevel', ...AUDIT], nullable: [] },
appsetting: { fields: ['appsettingid', '_parentappmoduleid_value', '_settingdefinitionid_value', 'value', 'componentstate', ...AUDIT], nullable: ['uniquename'], lookups: { parentappmoduleid: 'appmodules', settingdefinitionid: 'settingdefinitions' } },
organizationsetting: { fields: ['organizationsettingid', '_settingdefinitionid_value', 'value', 'uniquename', ...AUDIT], nullable: [], lookups: { settingdefinitionid: 'settingdefinitions' } },
+ // Reachable only in an org made with `{ fieldSecurity: true }` (FIELD_SECURITY_TABLES).
+ fieldsecurityprofile: { fields: ['fieldsecurityprofileid', 'name', 'ismanaged', ...AUDIT], nullable: ['description'] },
+ fieldpermission: { fields: ['fieldpermissionid', '_fieldsecurityprofileid_value', 'entityname', 'attributelogicalname', 'canread', 'cancreate', 'canupdate', ...AUDIT], nullable: ['canreadunmasked'], lookups: { fieldsecurityprofileid: 'fieldsecurityprofiles' } },
+ // Reachable only in an org made with `{ configuration: true }` (CONFIGURATION_TABLES). Every column a definition may leave empty is
+ // nullable: the build sets only what the spec declares. `collections` are the collection-valued navigations `$expand` may embed and a
+ // create may carry as a deep insert: the child set and the lookup on the child that points back.
+ environmentvariabledefinition: {
+ fields: ['environmentvariabledefinitionid', 'schemaname', 'type', 'isrequired', ...AUDIT],
+ nullable: ['displayname', 'description', 'defaultvalue', 'valueschema', 'apiid', 'connectorid', 'parameterkey', '_parentdefinitionid_value', 'secretstore', 'hint', 'learnmoreurl', 'inputcontrolconfig', 'ismanaged', 'statecode', 'statuscode'],
+ lookups: { parentdefinitionid: 'environmentvariabledefinitions' },
+ collections: { environmentvariabledefinition_environmentvariablevalue: { set: 'environmentvariablevalues', fk: '_environmentvariabledefinitionid_value' } },
+ },
+ environmentvariablevalue: { fields: ['environmentvariablevalueid', '_environmentvariabledefinitionid_value', ...AUDIT], nullable: ['value', 'schemaname', 'ismanaged', 'statecode', 'statuscode'], lookups: { environmentvariabledefinitionid: 'environmentvariabledefinitions' } },
+ connectionreference: {
+ fields: ['connectionreferenceid', 'connectionreferencelogicalname', ...AUDIT],
+ nullable: ['connectionreferencedisplayname', 'description', 'connectorid', '_customconnectorid_value', 'connectionid', 'connectionparametersconfig', 'connectionparametersetconfig', 'promptingbehavior', 'ismanaged', 'statecode', 'statuscode'],
+ },
+ customapi: {
+ fields: ['customapiid', 'uniquename', ...AUDIT],
+ nullable: ['name', 'displayname', 'description', 'bindingtype', 'boundentitylogicalname', 'isfunction', 'isprivate', 'allowedcustomprocessingsteptype', 'workflowsdkstepenabled', 'executeprivilegename', '_plugintypeid_value', 'ismanaged', 'statecode', 'statuscode'],
+ collections: {
+ CustomAPIRequestParameters: { set: 'customapirequestparameters', fk: '_customapiid_value' },
+ CustomAPIResponseProperties: { set: 'customapiresponseproperties', fk: '_customapiid_value' },
+ },
+ },
+ customapirequestparameter: { fields: ['customapirequestparameterid', 'uniquename', '_customapiid_value', ...AUDIT], nullable: ['name', 'displayname', 'description', 'type', 'logicalentityname', 'isoptional', 'ismanaged'], lookups: { customapiid: 'customapis' } },
+ customapiresponseproperty: { fields: ['customapiresponsepropertyid', 'uniquename', '_customapiid_value', ...AUDIT], nullable: ['name', 'displayname', 'description', 'type', 'logicalentityname', 'ismanaged'], lookups: { customapiid: 'customapis' } },
// The page tables are answered by the page fake (helpers/fake-genpage-server.js); their reads are checked here before it sees them.
uxagentproject: { fields: ['uxagentprojectid', 'name', 'versionnumber', 'componentstate'], nullable: ['description', 'createdon', 'modifiedon'] },
uxagentprojectfile: { fields: ['uxagentprojectfileid', 'filename', 'filetype', '_uxagentprojectid_value', 'versionnumber'], nullable: ['createdon', 'modifiedon'], lookups: { uxagentprojectid: 'uxagentprojects' } },
@@ -155,7 +218,8 @@ const READ_OPTIONS = {
navigation: ['$select', '$filter', '$orderby', '$top'],
unpublished: ['$select'],
unpublishedMany: ['$select', '$filter', '$orderby', '$top'],
- write: ['$select'],
+ // A create may `$expand` what it deep-inserted (a Custom API answers its new children's ids); expandsOf checks each navigation.
+ write: ['$select', '$expand'],
};
// The fixed ids a fresh environment hands out, so a test can name them.
@@ -199,14 +263,16 @@ function createLifecycleOrg(options = {}) {
onTableDeleted: (table) => tableDeleted(table),
});
+ // The system tables of this org: column security's two only when the test asked for them (FIELD_SECURITY_TABLES).
+ const systemTables = { ...SYSTEM_TABLES, ...(options.fieldSecurity ? FIELD_SECURITY_TABLES : {}), ...(options.configuration ? CONFIGURATION_TABLES : {}) };
const tableInfo = (logical) => {
- const system = SYSTEM_TABLES[logical];
+ const system = systemTables[logical];
if (system) return { logical, ...system };
const t = metadata.tables.get(logical);
return t ? { logical, set: t.EntitySetName, id: t.PrimaryIdAttribute, name: t.PrimaryNameAttribute, otc: t.ObjectTypeCode } : null;
};
const infoOfSet = (set) => {
- for (const [logical, t] of Object.entries(SYSTEM_TABLES)) if (t.set === set) return { logical, ...t };
+ for (const [logical, t] of Object.entries(systemTables)) if (t.set === set) return { logical, ...t };
for (const t of metadata.tables.values()) if (t.EntitySetName === set) return tableInfo(t.LogicalName);
return null;
};
@@ -371,7 +437,7 @@ function createLifecycleOrg(options = {}) {
if (!info) throw new Unmodelled(`no table has the entity set ${set}`);
const explicit = RECORD_SCHEMA[info.logical];
if (explicit) {
- return { info, fields: new Set(explicit.fields), nullable: new Set(explicit.nullable), lookups: explicit.lookups || {}, navigations: explicit.navigations || {}, expands: explicit.expands || {} };
+ return { info, fields: new Set(explicit.fields), nullable: new Set(explicit.nullable), lookups: explicit.lookups || {}, navigations: explicit.navigations || {}, expands: explicit.expands || {}, collections: explicit.collections || {} };
}
const table = metadata.tables.get(info.logical);
if (!table) throw new Unmodelled(`the table of ${set} has no definition`);
@@ -394,7 +460,7 @@ function createLifecycleOrg(options = {}) {
}
if (!fields.has(name)) nullable.add(name);
}
- return { info, fields, nullable, lookups, navigations: {}, expands: {} };
+ return { info, fields, nullable, lookups, navigations: {}, expands: {}, collections: {} };
}
const knows = (schema, name) => schema.fields.has(name) || schema.nullable.has(name);
// Refuses — before any row is enumerated — a read that names anything the set does not have: an option, a column (in `$select`,
@@ -516,18 +582,30 @@ function createLifecycleOrg(options = {}) {
// -> { "solutionid": "…", "uniquename": "…", "publisherid": { "publisherid": "…", "customizationprefix": "contoso" } }
// The navigations modelled are the lookups the lifecycle expands (RECORD_SCHEMA `expands`); any other is refused by name.
// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query/join-tables#expand-many-to-one-relationships
+ //
+ // A collection-valued navigation (RECORD_SCHEMA `collections`) embeds the child rows that point back at the row, each narrowed by its
+ // own `$select`, in the order they were made:
+ // /customapis(<id>)?$select=customapiid&$expand=CustomAPIRequestParameters($select=customapirequestparameterid,uniquename)
+ // -> { "customapiid": "…", "CustomAPIRequestParameters": [ { "customapirequestparameterid": "…", "uniquename": "In" } ] }
+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query/join-tables#expand-one-to-many-relationships
function expandsOf(schema, text, where) {
return metadata.parseExpand(text).map((item) => {
- const target = schema.expands[item.name];
+ const collection = schema.collections[item.name] || null;
+ const target = collection ? collection.set : schema.expands[item.name];
if (!target) throw new Unmodelled(`$expand=${item.name} on ${where} is not modelled`);
for (const option of Object.keys(item.opts)) if (option !== '$select') throw new Unmodelled(`$expand=${item.name}(${option}) on ${where} is not modelled`);
const related = schemaOf(target);
if (item.opts.$select !== undefined) for (const name of listOf(item.opts.$select)) if (!knows(related, name)) throw new Unmodelled(`${related.info.logical} has no column ${name} ($expand=${item.name} on ${where})`);
- return { ...item, target };
+ return { ...item, target, collection, parentKey: schema.info.id };
});
}
function withExpands(out, data, expands) {
for (const e of expands) {
+ if (e.collection) {
+ const parent = bare(data[e.parentKey]);
+ out[e.name] = [...rowsOf(e.target).values()].filter((row) => bare(row.data[e.collection.fk]) === parent).map((row) => shape(row, row.data, e.opts, infoOfSet(e.target), { saved: true }));
+ continue;
+ }
const id = data[`_${e.name}_value`];
const row = id && rowsOf(e.target).get(bare(id));
out[e.name] = row ? shape(row, row.data, e.opts, infoOfSet(e.target), { saved: true }) : null;
@@ -582,12 +660,30 @@ function createLifecycleOrg(options = {}) {
roles: () => ({ ismanaged: false, iscustomizable: { Value: true, CanBeChanged: true } }),
solutions: () => ({ ismanaged: false, isvisible: true }),
appactions: () => ({ ismanaged: false, statecode: 0, statuscode: 1 }),
+ environmentvariabledefinitions: () => ({ ismanaged: false, statecode: 0, statuscode: 1 }),
+ environmentvariablevalues: () => ({ ismanaged: false, statecode: 0, statuscode: 1 }),
+ connectionreferences: () => ({ ismanaged: false, statecode: 0, statuscode: 1 }),
+ customapis: () => ({ ismanaged: false, statecode: 0, statuscode: 1 }),
+ customapirequestparameters: () => ({ ismanaged: false }),
+ customapiresponseproperties: () => ({ ismanaged: false }),
};
function createRow(set, body, headers, query = {}) {
const info = infoOfSet(set);
if (!info) throw new Unmodelled(`no table has the entity set ${set}`);
- const data = { ...(CREATE_DEFAULTS[set] ? CREATE_DEFAULTS[set]() : {}), ...coerce(bindLookups(set, body)) };
+ // A deep insert: an array under a collection-valued navigation is the child rows, made in the same request and pointing back at the
+ // new row (`{ "uniquename": "contoso_Ping", "CustomAPIRequestParameters": [ { "uniquename": "In", … } ] }`).
+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-entity-web-api#create-related-table-rows-in-one-operation
+ const { collections } = schemaOf(set);
+ const own = { ...(body || {}) };
+ const children = [];
+ for (const [name, collection] of Object.entries(collections)) {
+ if (own[name] === undefined) continue;
+ if (!Array.isArray(own[name])) throw new Unmodelled(`a deep insert of ${name} that is not a list on ${set}`);
+ children.push([collection, own[name]]);
+ delete own[name];
+ }
+ const data = { ...(CREATE_DEFAULTS[set] ? CREATE_DEFAULTS[set]() : {}), ...coerce(bindLookups(set, own)) };
// A dashboard is a form of no table: the platform stores `objecttypecode` "none" for it.
if (set === 'systemforms' && Number(data.type) === 0 && !data.objecttypecode) data.objecttypecode = 'none';
const id = bare(data[info.id] || randomUUID());
@@ -602,11 +698,22 @@ function createLifecycleOrg(options = {}) {
if (data.statuscode === undefined) data.statuscode = 1;
}
const row = insertRow(set, { ...data, [info.id]: id, createdon: '2026-10-01T00:00:00Z', modifiedon: '2026-10-01T00:00:00Z' });
+ for (const [collection, items] of children) {
+ for (const item of items) {
+ const childInfo = infoOfSet(collection.set);
+ const child = { ...(CREATE_DEFAULTS[collection.set] ? CREATE_DEFAULTS[collection.set]() : {}), ...coerce(bindLookups(collection.set, item)), [collection.fk]: id };
+ const childId = bare(child[childInfo.id] || randomUUID());
+ if (rowsOf(collection.set).has(childId)) throw new Unmodelled(`a deep insert of an existing ${childInfo.logical} ${childId}`);
+ insertRow(collection.set, { ...child, [childInfo.id]: childId });
+ }
+ }
const solution = solutionHeader(headers);
if (solution && info.componentType) addComponentByName(solution, { objectid: id, componenttype: info.componentType });
const location = `${API}/${set}(${id})`;
- // `Prefer: return=representation` answers the row as created — narrowed by the request's `$select`, as a read would be.
- if (/return=representation/i.test(preferOf(headers))) return json(201, shape(row, row.data, query, info, { saved: true }), { 'odata-entityid': location, etag: etagOf(row.version) });
+ // `Prefer: return=representation` answers the row as created — narrowed by the request's `$select`, and with what its `$expand`
+ // names, as a read would be.
+ const expands = query.$expand !== undefined ? expandsOf(schemaOf(set), query.$expand, `POST /${set}`) : [];
+ if (/return=representation/i.test(preferOf(headers))) return json(201, withExpands(shape(row, row.data, query, info, { saved: true }), row.data, expands), { 'odata-entityid': location, etag: etagOf(row.version) });
return noContent({ 'odata-entityid': location, etag: etagOf(row.version) });
}
@@ -677,7 +784,7 @@ function createLifecycleOrg(options = {}) {
function recordPrivileges(table) {
for (const p of table.Privileges || []) insertRow('privileges', { privilegeid: p.PrivilegeId, name: p.Name, accessright: p.PrivilegeType, canbebasic: p.CanBeBasic, canbelocal: p.CanBeLocal, canbedeep: p.CanBeDeep, canbeglobal: p.CanBeGlobal });
}
- for (const [logical, info] of Object.entries(SYSTEM_TABLES)) seedSystemTable(logical, info);
+ for (const [logical, info] of Object.entries(systemTables)) seedSystemTable(logical, info);
// The two stock tables the platform relates every File and Image column to (fake-lifecycle-metadata.js mediaRelationshipOf), as
// definitions only: nothing reads or writes their rows. MEASURED: `fileattachment` reads back `IsCustomEntity: false`.
for (const [logical, otc] of [['fileattachment', 55], ['imagedescriptor', 1007]]) {
@@ -1032,6 +1139,8 @@ function createLifecycleOrg(options = {}) {
const info = infoOfSet(set);
if (!info) throw new Unmodelled(`${method} ${p}: no table has the entity set ${set}`);
if (key !== undefined) idOf(key, `${method} ${p}`);
+ // Column security is modelled for reading only: a write to a profile, a permission or a profile's links is not modelled.
+ if (method !== 'GET' && Object.values(FIELD_SECURITY_TABLES).some((t) => t.set === set)) throw new Unmodelled(`${method} ${p}: a write to column security is not modelled`);
if (!key && !rest) {
if (method === 'GET') return json(200, { value: readRows(set, query, { kind: 'collection', where: p }) });
if (method === 'POST') { checkRead(set, query, 'write', p); return createRow(set, body, headers, query); }
@@ -1346,6 +1455,10 @@ function createLifecycleOrg(options = {}) {
unpublished: () => [...sets].flatMap(([set, rows]) => (isLayered(set) ? [...rows.values()].filter((row) => row.publishedVersion !== row.version).map((row) => `${set} ${row.data.name || row.id}`) : [])),
// A row by name, saved layer: what the platform holds whatever is published.
find: (set, predicate) => [...rowsOf(set).values()].map((row) => row.data).filter(predicate),
+ // What a test sets up that no lifecycle request makes (a column security profile, its permissions, a second user): a row put in
+ // place as the platform holds it, and a component put in a solution, without a request — so neither is counted as a write.
+ seedRow: (set, data) => clone(insertRow(set, data).data),
+ seedComponent: (solutionName, component) => addComponentByName(solutionName, component),
};
}
diff --git a/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.js b/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.js
index a20366245..08c1ed194 100644
--- a/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.js
+++ b/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.js
@@ -8,11 +8,16 @@ const fs = require('node:fs');
const path = require('node:path');
const { performance } = require('node:perf_hooks');
const { createAzHttpClient } = require('../../lib/sdk-http-client.js');
+const { createPublicationBarrier } = require('../../lib/publication-barrier.js');
const { createMakerSdk: createVendoredMakerSdk, createNodeWorkspaceStorage } = require('../../lib/maker-sdk.js');
const { buildModelApp } = require('../../build-model-app.js');
const { verifySpec } = require('../../lib/verify-spec.js');
const { readerFor } = require('../../verify-model-app.js');
-const { appUniqueName } = require('../../lib/sdk-build.js');
+const { appUniqueName, protectedConfigurationInPlay } = require('../../lib/sdk-build.js');
+const { createDeferredManagedCreateGate, composeWriteGates } = require('../../lib/managed-create-transport.js');
+const { configurationSendOnce } = require('../../lib/configuration-transport.js');
+const { usesConfiguration } = require('../../lib/configuration-artifacts.js');
+const { connectionRowFromSdk } = require('../../list-connections.js');
const { makeGenpageSdk } = require('../../lib/genpage-sdk.js');
const { PHASES } = require('../../lib/stages.js');
const download = require('../../download-model-app.js');
@@ -150,10 +155,27 @@ function createLifecycleHarness(org, root, { createMakerSdk = createVendoredMake
// folder's workspace and recovers a form create whose answer was lost — and the deps its main() hands buildModelApp. `sdkWorkspace` is
// where that second one keeps its copies: the build's workspace, as the CLI makes it, unless a test says otherwise — the CLI makes no SDK
// for an apply its build lease refuses, so a second build a test starts beside a running one is given copies of its own.
- async function build(spec, { apply = true, publish = true, sampleData = true, verify = true, appFolder = appDir, workspace = workspaceDir, sdkWorkspace = workspace, languageCode = 1033 } = {}) {
- const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(throwaway('sdk-')), instanceUrl: org.origin, httpClient: client, solutionUniqueName: spec.solution.uniqueName, languageCode });
- const provisionSdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(apply ? sdkWorkspace : throwaway('preview-')), instanceUrl: org.origin, httpClient: client, languageCode, createRecovery: 'adoptExact' });
+ // `gated`: the build's client sends through the publication barrier the build is handed, as build-model-app.js makeSdk wires the
+ // CLI's (publicationBarrier.gateRequest). A stable build (createIdentity "stable-v1") needs it: it refuses to send a create it cannot
+ // tie to its draft at the transport (creates-stable-build.js). Off by default, so every other lifecycle test sends what it always did.
+ // `configurationBindings`: what build-model-app.js main reads from --deployment-settings (readDeploymentBindings) — the current values
+ // and connections the build binds to the spec's protected configuration. None by default, as a build without the option has none.
+ // Protected configuration in play (configurationIdentity "stable-v1", or a store still holding its state) is wired as main wires it:
+ // the deferred managed-create gate screens the build client's writes and is handed to the build, which binds it to its store, and a
+ // configuration write is sent once (configurationSendOnce). `connections` are the environment's connections the build may bind a
+ // reference to ({ connectionId, connectorId, displayName }, as the SDK lists them); the strict org does not model the listing.
+ // A build without protected configuration gets neither, so it sends what it always did.
+ async function build(spec, { apply = true, publish = true, sampleData = true, verify = true, appFolder = appDir, workspace = workspaceDir, sdkWorkspace = workspace, languageCode = 1033, gated = false, configurationBindings, connections } = {}) {
+ const publicationBarrier = gated ? createPublicationBarrier() : undefined;
+ const managedCreateGate = apply && protectedConfigurationInPlay(spec, { apply: true, env: org.origin, workspaceDir: workspace, appDir: appFolder }) ? createDeferredManagedCreateGate() : null;
+ const configured = managedCreateGate ? { sendOnce: (method, url) => configurationSendOnce(method, url), workflowEffectGate: composeWriteGates(managedCreateGate) } : {};
+ const buildClient = gated || managedCreateGate ? createAzHttpClient(org.origin, { getToken: () => TOKEN, request: publicationBarrier ? publicationBarrier.gateRequest(org.request) : org.request, sleep: async () => {}, ...configured }) : client;
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(throwaway('sdk-')), instanceUrl: org.origin, httpClient: buildClient, solutionUniqueName: spec.solution.uniqueName, languageCode });
+ const provisionSdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(apply ? sdkWorkspace : throwaway('preview-')), instanceUrl: org.origin, httpClient: buildClient, languageCode, createRecovery: 'adoptExact' });
await provisionSdk.initWorkspace();
+ // As makeSdk does: the configuration items are written through the solution-scoped instance, whose throwaway workspace the SDK
+ // refuses until it is prepared (a local write only). Only for a spec that declares them, so no other build changes.
+ if (usesConfiguration(spec)) await sdk.initWorkspace();
const genpage = makeGenpageSdk(org.origin, { httpClient: client });
const warnings = [];
const log = [];
@@ -161,8 +183,9 @@ function createLifecycleHarness(org, root, { createMakerSdk = createVendoredMake
const result = await buildModelApp(spec, {
apply, publish, sampleData, verify, phases: PHASES, profile: apply ? 'deploy' : 'plan', nonInteractive: false,
appDir: appFolder, env: org.origin, workspaceDir: workspace, preResolvedLanguageCode: apply ? languageCode : undefined,
+ ...(configurationBindings ? { configurationBindings } : {}),
}, {
- sdk, provisionSdk, genpage, sleep: async () => {}, warn: (m) => warnings.push(String(m)), log: (m) => log.push(String(m)), provisionedLanguages: async () => org.pageServer.languages.provisioned,
+ sdk, provisionSdk, genpage, ...(publicationBarrier ? { publicationBarrier } : {}), ...(managedCreateGate ? { managedCreateGate } : {}), ...(connections ? { connections: async () => connections.map(connectionRowFromSdk) } : {}), sleep: async () => {}, warn: (m) => warnings.push(String(m)), log: (m) => log.push(String(m)), provisionedLanguages: async () => org.pageServer.languages.provisioned,
verify: async (s, o) => verifySpec(s, readerFor(provisionSdk, appUniqueName(s), { genpage, workspaceDir: workspace }), o),
});
return { result, warnings, log };
diff --git a/plugins/model-apps/scripts/tests/lifecycle-matrix-real-bundle.test.js b/plugins/model-apps/scripts/tests/lifecycle-matrix-real-bundle.test.js
index dbd78d994..b7d7ada63 100644
--- a/plugins/model-apps/scripts/tests/lifecycle-matrix-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/lifecycle-matrix-real-bundle.test.js
@@ -209,7 +209,7 @@ const BUDGET = {
// What verify checks, by kind: a kind that stops being checked (or is checked fewer times) fails here even though verify still passes.
const VERIFY_CHECKS = {
entity: 3, column: 18, 'status-reason': 1, 'alternate-key': 1, relationship: 3,
- view: 3, 'view-columns': 3, 'view-filters': 3, 'view-sort': 1, chart: 1,
+ view: 3, 'view-columns': 3, 'view-filters': 3, 'view-sort': 1, chart: 1, 'chart-type': 1, 'chart-data': 1, 'chart-description': 1,
form: 4, 'form-identities': 4, 'form-default': 2, 'form-order': 1, 'form-order-served': 1, 'form-timeline': 1,
dashboard: 1, command: 1, 'web-resource': 2,
subarea: 4, 'subarea-dashboard-launcher': 1, 'app-table-component': 4, page: 1, 'page-subarea': 1,
diff --git a/plugins/model-apps/scripts/tests/page-scroll.test.js b/plugins/model-apps/scripts/tests/page-scroll.test.js
index d39e3a339..043bcd73d 100644
--- a/plugins/model-apps/scripts/tests/page-scroll.test.js
+++ b/plugins/model-apps/scripts/tests/page-scroll.test.js
@@ -12,8 +12,9 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
+const os = require('node:os');
const path = require('node:path');
-const { execFileSync } = require('node:child_process');
+const { execFileSync, spawnSync } = require('node:child_process');
const { analyzePageScroll, pageScrollProblems, REMEDY_KEYS } = require('../lib/page-scroll.js');
const { loadVendoredTypeScript } = require('../lib/typescript-compiler.js');
@@ -46,6 +47,9 @@ const SCROLLS = "height: '100%', overflowY: 'auto', boxSizing: 'border-box'";
const FLEX_COLUMN = "display: 'flex', flexDirection: 'column'";
// Content taller than any host.
const TALL = '<div style={{ height: 2000 }}><Text>end</Text></div>';
+// A root whose height and minHeight are the CSS texts given; JSON.stringify spells each as a TSX string literal, so a backslash in the CSS
+// (String.raw`--x\ A`) reaches the page as one.
+const heightAndMin = (height, min) => page('', ` return (<div style={{ height: ${JSON.stringify(height)}, minHeight: ${JSON.stringify(min)}, overflowY: 'auto' }}>${TALL}</div>);`);
// [name, source, verdict]. Every case that is not a pass is also a case of the remedy invariant below.
const CASES = [
@@ -153,6 +157,57 @@ const CASES = [
['a minHeight in rem smaller than the height', page('', ` return (<div style={{ height: '30rem', minHeight: '10rem', overflowY: 'auto' }}>${TALL}</div>);`), 'pass'],
['a minHeight in rem larger than the height', page('', ` return (<div style={{ height: '30rem', minHeight: '40rem', overflowY: 'auto' }}>${TALL}</div>);`), 'fail'],
['a minHeight that is the same calc() as the height', page('', ` return (<div style={{ height: 'calc(100% - 64px)', minHeight: 'calc(100% - 64px)', overflowY: 'auto' }}>${TALL}</div>);`), 'pass'],
+ // Keywords, units and function names are not case-sensitive in CSS, but a custom property name is: `--height` and `--HEIGHT` are two
+ // properties, so a minHeight that names the other one may be any size. A value with a var() is compared byte for byte, so the same var()
+ // in another case or spacing is refused (not proven) too; the remedy passes those.
+ ['a minHeight whose var() names the height\'s custom property in another case', page('', ` return (<div style={{ height: 'calc(var(--height))', minHeight: 'calc(var(--HEIGHT))', overflowY: 'auto' }}>${TALL}</div>);`), 'unproven:min-height'],
+ ['a minHeight that is byte for byte the same var() as the height', page('', ` return (<div style={{ height: 'calc(var(--Height))', minHeight: 'calc(var(--Height))', overflowY: 'auto' }}>${TALL}</div>);`), 'pass'],
+ ['a minHeight that is the same var() as the height but for the case of its functions (refused, not proven)', page('', ` return (<div style={{ height: 'calc(var(--Height))', minHeight: 'CALC(VAR(--Height))', overflowY: 'auto' }}>${TALL}</div>);`), 'unproven:min-height'],
+ ['a minHeight that is the same var() as the height but for its spacing (refused, not proven)', heightAndMin('calc(var(--h))', 'calc( var(--h) )'), 'unproven:min-height'],
+ ['a minHeight that is the same calc() as the height in another case', page('', ` return (<div style={{ height: 'CALC(100% - 64PX)', minHeight: 'calc(100% - 64px)', overflowY: 'auto' }}>${TALL}</div>);`), 'pass'],
+ ['a minHeight in PX not larger than a height in px', page('', ` return (<div style={{ height: '480px', minHeight: '300PX', overflowY: 'auto' }}>${TALL}</div>);`), 'pass'],
+ ['a minHeight of Auto under height 100%', rooted(`${SCROLLS}, minHeight: 'Auto'`), 'pass'],
+ ['BORDER-BOX keeps the padding inside', rooted("height: '100%', overflowY: 'auto', padding: '16px', boxSizing: 'BORDER-BOX'"), 'pass'],
+ // Of an overflowY and an overflow on two classes only an agreement is read, and two custom property names in another case do not agree.
+ ['overflowY and overflow on two classes naming one custom property in another case', page(` root: { height: '100%', boxSizing: 'border-box' },\n a: { overflowY: 'var(--Scroll)' },\n b: { overflow: 'var(--scroll)' },`, ` return <div className={mergeClasses(styles.root, styles.a, styles.b)}>${TALL}</div>;`), 'unproven:conflicting-keys'],
+ ['overflowY and overflow on two classes that agree but for case', page(` root: { height: '100%', boxSizing: 'border-box' },\n a: { overflowY: 'AUTO' },\n b: { overflow: 'auto' },`, ` return <div className={mergeClasses(styles.root, styles.a, styles.b)}>${TALL}</div>;`), 'pass'],
+ // A custom property name may hold a CSS escape, and an escaped space, comma or parenthesis — or the space that ends a hex escape — is part
+ // of the name: `--x\ A` and `--x\ a` are two properties. Such text, or a comment, is compared byte for byte: anything else is not proven,
+ // which refuses two spellings of one name too (`--\4A` and `--\4a`, a comment in another case); the remedy passes those.
+ ['a minHeight naming an escaped-space custom property in another case', heightAndMin(String.raw`calc(var(--x\ A))`, String.raw`calc(var(--x\ a))`), 'unproven:min-height'],
+ ['a minHeight naming an escaped-comma custom property in another case', heightAndMin(String.raw`calc(var(--x\,A))`, String.raw`calc(var(--x\,a))`), 'unproven:min-height'],
+ ['a minHeight naming an escaped-parenthesis custom property in another case', heightAndMin(String.raw`calc(var(--x\(A))`, String.raw`calc(var(--x\(a))`), 'unproven:min-height'],
+ ['a minHeight naming a custom property whose hex escape ends in a space, in another case', heightAndMin(String.raw`calc(var(--\41 B))`, String.raw`calc(var(--\41 b))`), 'unproven:min-height'],
+ ['a minHeight naming one custom property through hex escapes in another case (refused, not proven)', heightAndMin(String.raw`calc(var(--\4A))`, String.raw`calc(var(--\4a))`), 'unproven:min-height'],
+ ['a minHeight naming one custom property beside a comment in another case (refused, not proven)', heightAndMin('calc(var(--height/**UPPER*/))', 'calc(var(--height/**upper*/))'), 'unproven:min-height'],
+ ['a minHeight that is byte for byte the height with an escaped custom property', heightAndMin(String.raw`calc(var(--x\ A))`, String.raw`calc(var(--x\ A))`), 'pass'],
+ ['a minHeight that is byte for byte the height with a comment', heightAndMin('calc(var(--height/**UPPER*/))', 'calc(var(--height/**UPPER*/))'), 'pass'],
+ ['overflowY and overflow on two classes naming escaped custom properties in another case', page(` root: { height: '100%', boxSizing: 'border-box' },\n a: { overflowY: ${JSON.stringify(String.raw`var(--x\,A)`)} },\n b: { overflow: ${JSON.stringify(String.raw`var(--x\,a)`)} },`, ` return <div className={mergeClasses(styles.root, styles.a, styles.b)}>${TALL}</div>;`), 'unproven:conflicting-keys'],
+ // Escapes can spell the `--` of a name too (`\2d \2d Height`, `\-\-Height`, `-\-Height` are `--Height`), so the comparison never looks for a
+ // name: any var(), backslash or comment makes it byte for byte.
+ ['a minHeight naming the height\'s custom property in another case, both hyphens hex-escaped', heightAndMin(String.raw`calc(var(\2d \2d Height))`, String.raw`calc(var(\2d \2d height))`), 'unproven:min-height'],
+ ['a minHeight naming the height\'s custom property in another case, both hyphens escaped', heightAndMin(String.raw`calc(var(\-\-Height))`, String.raw`calc(var(\-\-height))`), 'unproven:min-height'],
+ ['a minHeight naming the height\'s custom property in another case, the second hyphen escaped', heightAndMin(String.raw`calc(var(-\-Height))`, String.raw`calc(var(-\-height))`), 'unproven:min-height'],
+ ['a minHeight naming the height\'s custom property in another case, the first hyphen escaped', heightAndMin(String.raw`calc(var(\--Height))`, String.raw`calc(var(\--height))`), 'unproven:min-height'],
+ ['a minHeight that is byte for byte the height with escaped hyphens', heightAndMin(String.raw`calc(var(\-\-Height))`, String.raw`calc(var(\-\-Height))`), 'pass'],
+ ['a minHeight that is the same calc() as the height but for a comment in another case (refused, not proven)', heightAndMin('calc(100% /*A*/ - 64px)', 'calc(100% /*a*/ - 64px)'), 'unproven:min-height'],
+ ['overflowY and overflow on two classes naming custom properties in another case through escaped hyphens', page(` root: { height: '100%', boxSizing: 'border-box' },\n a: { overflowY: ${JSON.stringify(String.raw`var(\-\-Scroll)`)} },\n b: { overflow: ${JSON.stringify(String.raw`var(\-\-scroll)`)} },`, ` return <div className={mergeClasses(styles.root, styles.a, styles.b)}>${TALL}</div>;`), 'unproven:conflicting-keys'],
+ ['overflowY and overflow on two classes with the same var() but for the case of its function', page(` root: { height: '100%', boxSizing: 'border-box' },\n a: { overflowY: 'VAR(--Scroll)' },\n b: { overflow: 'var(--Scroll)' },`, ` return <div className={mergeClasses(styles.root, styles.a, styles.b)}>${TALL}</div>;`), 'unproven:conflicting-keys'],
+ ['overflowY and overflow on two classes with byte for byte the same var()', page(` root: { height: '100%', boxSizing: 'border-box' },\n a: { overflowY: 'var(--Scroll)' },\n b: { overflow: 'var(--Scroll)' },`, ` return <div className={mergeClasses(styles.root, styles.a, styles.b)}>${TALL}</div>;`), 'unproven:unread-value'],
+ // An env() name is case-sensitive too (an attr() name may be), and an env name the host does not define takes its fallback, so
+ // `calc(100% - env(a, -2000px))` and the same with `A` are not proven to be one value: a text with an env() or attr() is compared byte
+ // for byte like one with a var(). That refuses another case or spacing of one value as well (not proven); the remedy passes those.
+ ['a minHeight whose nested env() names another environment variable in another case', heightAndMin('calc(100% - env(safe-area-inset-bottom, -2000px))', 'calc(100% - env(SAFE-AREA-INSET-BOTTOM, -2000px))'), 'unproven:min-height'],
+ ['a minHeight that is byte for byte the height with a nested env()', heightAndMin('calc(100% - env(safe-area-inset-bottom, 0px))', 'calc(100% - env(safe-area-inset-bottom, 0px))'), 'pass'],
+ ['a minHeight that is the same env() as the height but for the case of its function (refused, not proven)', heightAndMin('calc(100% - env(safe-area-inset-bottom))', 'CALC(100% - ENV(safe-area-inset-bottom))'), 'unproven:min-height'],
+ ['a minHeight that is the same env() as the height but for its spacing (refused, not proven)', heightAndMin('calc(100% - env(safe-area-inset-bottom))', 'calc(100% - env( safe-area-inset-bottom ))'), 'unproven:min-height'],
+ ['a minHeight whose attr() argument differs in case (refused, not proven)', heightAndMin('calc(attr(data-h px, 400px))', 'calc(attr(DATA-H px, 400px))'), 'unproven:min-height'],
+ ['a minHeight that is byte for byte the height with an attr()', heightAndMin('calc(attr(data-h px, 400px))', 'calc(attr(data-h px, 400px))'), 'pass'],
+ ['a minHeight that is the same attr() as the height but for the case of its function (refused, not proven)', heightAndMin('calc(attr(data-h px, 400px))', 'calc(ATTR(data-h px, 400px))'), 'unproven:min-height'],
+ ['a minHeight with an env() beside a height without one', heightAndMin('calc(100% - 64px)', 'calc(100% - env(safe-area-inset-bottom, 64px))'), 'unproven:min-height'],
+ ['overflowY and overflow on two classes naming one env() in another case', page(` root: { height: '100%', boxSizing: 'border-box' },\n a: { overflowY: 'env(Scroll)' },\n b: { overflow: 'env(scroll)' },`, ` return <div className={mergeClasses(styles.root, styles.a, styles.b)}>${TALL}</div>;`), 'unproven:conflicting-keys'],
+ ['overflowY and overflow on two classes with the same attr() but for the case of its function', page(` root: { height: '100%', boxSizing: 'border-box' },\n a: { overflowY: 'ATTR(data-scroll)' },\n b: { overflow: 'attr(data-scroll)' },`, ` return <div className={mergeClasses(styles.root, styles.a, styles.b)}>${TALL}</div>;`), 'unproven:conflicting-keys'],
+ ['overflowY and overflow on two classes with byte for byte the same env()', page(` root: { height: '100%', boxSizing: 'border-box' },\n a: { overflowY: 'env(scroll)' },\n b: { overflow: 'env(scroll)' },`, ` return <div className={mergeClasses(styles.root, styles.a, styles.b)}>${TALL}</div>;`), 'unproven:unread-value'],
['a minHeight in % smaller than the height', page('', ` return (<div style={{ height: '50%', minHeight: '25%', overflowY: 'auto' }}>${TALL}</div>);`), 'pass'],
['a minHeight in rem under a height in px', page('', ` return (<div style={{ height: '480px', minHeight: '10rem', overflowY: 'auto' }}>${TALL}</div>);`), 'unproven:min-height'],
['a minHeight given a token', rooted(`${SCROLLS}, minHeight: tokens.spacingVerticalXXXL`), 'unproven:unread-value'],
@@ -183,6 +238,88 @@ for (const [name, source, expected] of CASES) {
});
}
+// A padded box that fills its container is refused either way, but one whose other bound is a fixed length (height "100%" under maxHeight
+// "400px") is min(container, 400px) tall plus its padding: it overhangs only a container shorter than 400px plus that padding, so its
+// message says the end may be cut off, and when. So does a box capped the other way round (height "400px" under maxHeight "100%") or one
+// that fills by a calc() under a fixed maxHeight. Every other padding message is as it was.
+test('page-scroll: the padding message says the end may be cut off only where a fixed bound caps the box, and is unchanged elsewhere', () => {
+ const message = (style) => {
+ const problems = pageScrollProblems(page('', ` return (<div style={{ ${style}, overflowY: 'auto', padding: 16 }}>${TALL}</div>);`));
+ assert.deepEqual(problems.map((p) => p.code), ['scroll-context-padding'], style);
+ return problems[0].message;
+ };
+ const how = 'Write boxSizing: "border-box" as the last key of the inline style of that <div> and make style its last attribute (references/rules.md, "Page Layout").';
+ const may = (fills, key, cap) => `the page scrolls, but its <div> at line 8 fills its container (${fills}) up to its ${key} (${cap}) and has vertical padding in the default content-box model, so in a container shorter than ${cap} plus that padding it is taller than its container, and the end of the page may be cut off below the visible area. ${how}`;
+ const stays = (fills) => `the page scrolls, but its <div> at line 8 fills its container (${fills}) and has vertical padding in the default content-box model, so it is taller than its container by that padding and the end of the page stays cut off below the visible area. ${how}`;
+ assert.equal(message("height: '100%', maxHeight: '400px'"), may('100%', 'maxHeight', '400px'));
+ assert.equal(message("height: '100%', maxHeight: 400"), may('100%', 'maxHeight', '400px'));
+ assert.equal(message("height: '100%', maxHeight: '30rem', minHeight: 0"), may('100%', 'maxHeight', '30rem'));
+ assert.equal(message("height: '400px', maxHeight: '100%'"), may('100%', 'height', '400px'));
+ assert.equal(message("height: 'calc(100% - 8px)', maxHeight: '400px'"), may('calc(100% - 8px)', 'maxHeight', '400px'));
+ // Unchanged: nothing caps the box, the cap is not a fixed length (150%, 100vh, a token), or a minimum may hold it at the container's height.
+ assert.equal(message("height: '100%'"), stays('100%'));
+ assert.equal(message("maxHeight: '100%'"), stays('100%'));
+ assert.equal(message("height: 'calc(100% - 8px)'"), stays('calc(100% - 8px)'));
+ assert.equal(message("height: '100%', maxHeight: '100%'"), stays('100%'));
+ assert.equal(message("height: '100%', maxHeight: '150%'"), stays('100%'));
+ assert.equal(message("height: '100%', maxHeight: '100vh'"), stays('100%'));
+ assert.equal(message("height: '100%', maxHeight: tokens.spacingVerticalXXXL"), stays('100%'));
+ assert.equal(message("height: '100%', maxHeight: '400px', minHeight: '100%'"), stays('100%'));
+});
+
+// The CLI on the escaped custom property pages: a generated page is refused (exit 3), and a page the run did not generate keeps exit 0
+// with the problem as a note.
+test('page-scroll: check-griffel-styles.js refuses a page whose minHeight names an escaped custom property in another case, and notes it with --existing', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'page-scroll-cli-'));
+ try {
+ const pairs = [[String.raw`--x\ A`, String.raw`--x\ a`], [String.raw`--x\,A`, String.raw`--x\,a`], [String.raw`--x\(A`, String.raw`--x\(a`], [String.raw`--\41 B`, String.raw`--\41 b`],
+ [String.raw`\2d \2d Height`, String.raw`\2d \2d height`], [String.raw`\-\-Height`, String.raw`\-\-height`], [String.raw`-\-Height`, String.raw`-\-height`]];
+ pairs.forEach(([h, m], i) => {
+ const file = path.join(dir, `page${i}.tsx`);
+ fs.writeFileSync(file, heightAndMin(`calc(var(${h}))`, `calc(var(${m}))`));
+ for (const existing of [false, true]) {
+ const r = spawnSync(process.execPath, [path.join(PLUGIN, 'scripts', 'check-griffel-styles.js'), '--file', file, ...(existing ? ['--existing'] : [])], { encoding: 'utf8' });
+ const out = JSON.parse(r.stdout);
+ const reported = (existing ? out.notes : out.problems) || [];
+ assert.equal(r.status, existing ? 0 : 3, `${h} ${existing}`);
+ assert.deepEqual(reported.map((p) => `${p.code}:${p.reason}`), ['scroll-context-unproven:min-height'], `${h} ${existing}`);
+ }
+ });
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+// The same on the env() and attr() pages: the exit code and the note are those of the custom property pages.
+test('page-scroll: check-griffel-styles.js refuses a page whose minHeight names an env() or attr() in another case, and notes it with --existing', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'page-scroll-cli-'));
+ try {
+ const pairs = [['calc(100% - env(safe-area-inset-bottom, -2000px))', 'calc(100% - env(SAFE-AREA-INSET-BOTTOM, -2000px))'], ['calc(attr(data-h px, 400px))', 'calc(attr(DATA-H px, 400px))']];
+ pairs.forEach(([h, m], i) => {
+ const file = path.join(dir, `page${i}.tsx`);
+ fs.writeFileSync(file, heightAndMin(h, m));
+ for (const existing of [false, true]) {
+ const r = spawnSync(process.execPath, [path.join(PLUGIN, 'scripts', 'check-griffel-styles.js'), '--file', file, ...(existing ? ['--existing'] : [])], { encoding: 'utf8' });
+ const out = JSON.parse(r.stdout);
+ const reported = (existing ? out.notes : out.problems) || [];
+ assert.equal(r.status, existing ? 0 : 3, `${h} ${existing}`);
+ assert.deepEqual(reported.map((p) => `${p.code}:${p.reason}`), ['scroll-context-unproven:min-height'], `${h} ${existing}`);
+ }
+ });
+ // The byte-for-byte same text passes in both modes.
+ const same = path.join(dir, 'same.tsx');
+ fs.writeFileSync(same, heightAndMin('calc(100% - env(safe-area-inset-bottom, 0px))', 'calc(100% - env(safe-area-inset-bottom, 0px))'));
+ for (const existing of [false, true]) {
+ const r = spawnSync(process.execPath, [path.join(PLUGIN, 'scripts', 'check-griffel-styles.js'), '--file', same, ...(existing ? ['--existing'] : [])], { encoding: 'utf8' });
+ assert.equal(r.status, 0, String(existing));
+ const out = JSON.parse(r.stdout);
+ assert.deepEqual([...(out.problems || []), ...(out.notes || [])].map((p) => p.code).filter((c) => c.startsWith('scroll-context')), [], String(existing));
+ }
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
test('page-scroll: the work item\'s dashboard — default export → error boundary class → body component → a flex column root — has no scroll context', () => {
const source = `${HEAD}const useStyles = makeStyles({\n root: { display: 'flex', flexDirection: 'column', gap: tokens.spacingVerticalL, padding: tokens.spacingHorizontalL },\n card: { padding: '8px' },\n});\nclass PageErrorBoundary extends React.Component<{ children: React.ReactNode }> {\n render() { return this.props.children; }\n}\nfunction PageBody() {\n const styles = useStyles();\n return (\n <div className={styles.root}>\n {[1, 2].map((n) => <Card key={n} className={styles.card}><Text>{n}</Text></Card>)}\n </div>\n );\n}\nexport default function GeneratedComponent() {\n return <PageErrorBoundary><PageBody /></PageErrorBoundary>;\n}\n`;
const problems = pageScrollProblems(source);
diff --git a/plugins/model-apps/scripts/tests/safe-fs.test.js b/plugins/model-apps/scripts/tests/safe-fs.test.js
index e3f418ca1..c7546e3b2 100644
--- a/plugins/model-apps/scripts/tests/safe-fs.test.js
+++ b/plugins/model-apps/scripts/tests/safe-fs.test.js
@@ -9,7 +9,7 @@ const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
-const { assertSafeOutputDir, assertPlainFileTarget, writeFileSafe, appendFileSafe, removeFileSafe, removeTreeWithRetry } = require('../lib/safe-fs.js');
+const { assertSafeOutputDir, assertPlainFileTarget, assertFileReplaceable, writeFileSafe, appendFileSafe, removeFileSafe, removeTreeWithRetry } = require('../lib/safe-fs.js');
const dirs = [];
test.after(() => {
@@ -838,4 +838,60 @@ test('removeTreeWithRetry never throws: what it cannot remove it describes, what
assert.strictEqual(removeTreeWithRetry('somewhere', { fs: { rmSync: () => { throw 'a string'; } } }), 'UNKNOWN');
assert.strictEqual(removeTreeWithRetry('somewhere', { fs: { rmSync: () => { throw Object.assign(new Error('x'), { code: 42 }); } } }), 42);
assert.strictEqual(removeTreeWithRetry('somewhere', { fs: { rmSync: () => { throw null; } } }), 'UNKNOWN');
-});
\ No newline at end of file
+});
+
+// ── assertFileReplaceable: the look a download takes at app-spec.json before it replaces pages/ ──────────────────────────────────────
+
+// `fs` with some of its methods replaced.
+function fsWith(overrides) {
+ const wrapped = Object.create(fs);
+ for (const [name, value] of Object.entries(overrides)) Object.defineProperty(wrapped, name, { value, writable: true });
+ return wrapped;
+}
+
+test('assertFileReplaceable makes, then removes, an empty sibling of its own to learn the folder takes a new file: a moment\'s lock on its removal is waited out on Windows, and nothing is left', () => {
+ const dir = tmp();
+ const spec = path.join(dir, 'app-spec.json');
+ fs.writeFileSync(spec, '{"maker":"unchanged"}');
+ let calls = 0;
+ const answer = assertFileReplaceable(spec, { fs: fsWith({ unlinkSync(p) {
+ calls += 1;
+ if (calls === 1 && process.platform === 'win32') throw Object.assign(new Error('EBUSY: injected'), { code: 'EBUSY' });
+ fs.unlinkSync(p);
+ } }) });
+ assert.strictEqual(answer, path.join(fs.realpathSync.native(dir), 'app-spec.json'));
+ assert.strictEqual(calls, process.platform === 'win32' ? 2 : 1);
+ assert.deepStrictEqual(fs.readdirSync(dir), ['app-spec.json']);
+ assert.strictEqual(fs.readFileSync(spec, 'utf8'), '{"maker":"unchanged"}');
+});
+
+for (const code of ['EIO', 'EACCES']) {
+ test(`assertFileReplaceable refuses when the empty sibling it made cannot be removed (${code}): the refusal names that file exactly and says it is the download's own, empty and can be deleted`, () => {
+ const dir = tmp();
+ const spec = path.join(dir, 'app-spec.json');
+ fs.writeFileSync(spec, '{"maker":"unchanged"}');
+ let probe = null;
+ const cause = Object.assign(new Error(`${code}: injected`), { code });
+ let thrown = null;
+ try {
+ assertFileReplaceable(spec, { fs: fsWith({
+ openSync(p, ...args) { probe = String(p); return fs.openSync(p, ...args); },
+ unlinkSync() { throw cause; },
+ }) });
+ } catch (e) {
+ thrown = e;
+ }
+ const left = fs.readdirSync(dir).filter((n) => n !== 'app-spec.json');
+ assert.ok(thrown, 'the look does not pass while its own file is left behind');
+ assert.strictEqual(thrown.code, 'IO_ERROR');
+ assert.strictEqual(thrown.reason, 'probe-not-removed');
+ assert.strictEqual(thrown.cause, cause);
+ assert.deepStrictEqual(left, [path.basename(probe)]);
+ assert.match(left[0], /^\.app-spec\.json\.\d+\.[0-9a-f]{8}\.tmp$/);
+ assert.strictEqual(fs.statSync(probe).size, 0);
+ assert.ok(thrown.message.includes(probe), thrown.message);
+ assert.ok(thrown.message.includes(`(${code})`), thrown.message);
+ assert.match(thrown.message, /an empty file this download made .*can be deleted/);
+ assert.strictEqual(fs.readFileSync(spec, 'utf8'), '{"maker":"unchanged"}');
+ });
+}
diff --git a/plugins/model-apps/scripts/tests/sdk-build-declared-bpf.test.js b/plugins/model-apps/scripts/tests/sdk-build-declared-bpf.test.js
index 0ef9da400..c98e433bb 100644
--- a/plugins/model-apps/scripts/tests/sdk-build-declared-bpf.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-build-declared-bpf.test.js
@@ -1036,53 +1036,61 @@ test('a managed download with nothing to write as fragments writes nothing there
});
});
+// The managed download of an app with one declared process and one generative page into a folder that holds a maker's edit of that page
+// and an older spec: the real page download runs over a page backend, and the restore input is the flow this wire built. Call inside
+// withBpf. `run()` downloads; `staged()` says whether the download was asked to stage its pages; `stagingLeft()` lists staging folders left.
+async function managedPagesFixture() {
+ const { runDownload } = require('../download-model-app.js');
+ const { currentReadSdk } = require('./helpers/app-membership-sdk.js');
+ const { fakeGenpage } = require('./helpers/fake-genpage.js');
+ // Its own flow, persona and app id, so the tests that use it stand without the persona-proof tests (and their constants) above.
+ const roled = { ...FLOW, securityRoles: { personas: ['Dispatcher'] } };
+ const dispatcher = { persona: 'Dispatcher', jobs: [{ name: 'Triage tickets', privileges: [{ entity: 'new_ticket', access: ['read', 'write'] }] }] };
+ const appId = '00000000-0000-0000-0000-00000000a333';
+ const wire = createWorkflowWire();
+ const dir = makeTempDir('declared-bpf-');
+ assert.equal((await build(wire, dir, { ...specWith([roled]), personas: [dispatcher] })).err, undefined);
+ const out = makeTempDir('declared-bpf-');
+ const pid = '00000000-0000-4000-8000-00000000bbbb';
+ const pageFile = path.join(out, 'pages', pid, 'page.tsx');
+ fs.mkdirSync(path.dirname(pageFile), { recursive: true });
+ fs.writeFileSync(pageFile, 'MAKER EDIT THAT MUST SURVIVE FAILURE');
+ const oldSpec = JSON.stringify({ ...specWith([]), pages: [{ key: 'old', name: 'Page', pageId: pid }] });
+ fs.writeFileSync(path.join(out, 'app-spec.json'), oldSpec);
+ const xml = `<SiteMap><Area><Group><SubArea GenPageId="${pid}" Title="Page"/><SubArea Entity="new_ticket"/></Group></Area></SiteMap>`;
+ const layer = '00000000-0000-4000-8000-00000000cccc';
+ const pageSdk = currentReadSdk({
+ fetchArtifact: async () => ({ name: 'BP App', uniqueName: APP, siteMap: { areas: [{ title: 'Main', groups: [{ title: 'Records', subAreas: [{ type: 'GenPage', genPageId: pid, title: 'Page' }, { type: 'Entity', entity: 'new_ticket' }] }] }] } }),
+ queryRecords: async (logical) => {
+ if (logical === 'appmodule') return [{ appmoduleid: appId, appmoduleidunique: layer, uniquename: APP }];
+ if (logical === 'appmodulecomponent') return [{ objectid: '00000000-0000-4000-8000-00000000dddd', componenttype: 62 }];
+ if (logical === 'sitemap') return [{ sitemapxml: xml }];
+ return [];
+ },
+ fetchEntityMetadata: async (logical) => ({ schemaName: logical, displayName: 'Ticket', primaryNameAttribute: 'new_subject' }),
+ }, { appId, layerId: layer, sitemapXml: xml });
+ const source = 'export default function Page(){return null;}';
+ const genpage = fakeGenpage({ pages: [{ pageId: pid, name: 'Page', source }] });
+ let staged;
+ const run = () => download(wire, out, ['--include-managed', '--managed-manifest', storeFileOf(dir)], {
+ // The real page download, over a page backend; the restore input is the flow this wire built.
+ runDownload: async (args) => {
+ const real = await runDownload({ ...args, sdk: pageSdk, genpage });
+ assert.equal(real.ok, true, JSON.stringify(real));
+ staged = args.stagePages;
+ return { ...real, spec: specWith([]) };
+ },
+ });
+ const stagingLeft = () => fs.readdirSync(out).filter((n) => n.startsWith('.download-pages.'));
+ return { out, pageFile, oldSpec, source, run, stagingLeft, staged: () => staged };
+}
+
test('a fragments file that cannot be written leaves every output that was there as it was: the page tree, the spec and the baseline are published only after it', async () => {
await withBpf(true, async () => {
- const { runDownload } = require('../download-model-app.js');
- const { currentReadSdk } = require('./helpers/app-membership-sdk.js');
- const { fakeGenpage } = require('./helpers/fake-genpage.js');
- // Its own flow, persona and app id, so this test stands without the persona-proof tests (and their constants) above.
- const roled = { ...FLOW, securityRoles: { personas: ['Dispatcher'] } };
- const dispatcher = { persona: 'Dispatcher', jobs: [{ name: 'Triage tickets', privileges: [{ entity: 'new_ticket', access: ['read', 'write'] }] }] };
- const appId = '00000000-0000-0000-0000-00000000a333';
- const wire = createWorkflowWire();
- const dir = makeTempDir('declared-bpf-');
- assert.equal((await build(wire, dir, { ...specWith([roled]), personas: [dispatcher] })).err, undefined);
- const out = makeTempDir('declared-bpf-');
- const pid = '00000000-0000-4000-8000-00000000bbbb';
- const pageFile = path.join(out, 'pages', pid, 'page.tsx');
- fs.mkdirSync(path.dirname(pageFile), { recursive: true });
- fs.writeFileSync(pageFile, 'MAKER EDIT THAT MUST SURVIVE FAILURE');
- const oldSpec = JSON.stringify({ ...specWith([]), pages: [{ key: 'old', name: 'Page', pageId: pid }] });
- fs.writeFileSync(path.join(out, 'app-spec.json'), oldSpec);
+ const { out, pageFile, oldSpec, source, run, stagingLeft, staged } = await managedPagesFixture();
// A file where the fragments folder goes: no new file can be made in it.
const ws = path.join(out, '.maker-workspace');
fs.writeFileSync(ws, 'maker notes');
- const xml = `<SiteMap><Area><Group><SubArea GenPageId="${pid}" Title="Page"/><SubArea Entity="new_ticket"/></Group></Area></SiteMap>`;
- const layer = '00000000-0000-4000-8000-00000000cccc';
- const pageSdk = currentReadSdk({
- fetchArtifact: async () => ({ name: 'BP App', uniqueName: APP, siteMap: { areas: [{ title: 'Main', groups: [{ title: 'Records', subAreas: [{ type: 'GenPage', genPageId: pid, title: 'Page' }, { type: 'Entity', entity: 'new_ticket' }] }] }] } }),
- queryRecords: async (logical) => {
- if (logical === 'appmodule') return [{ appmoduleid: appId, appmoduleidunique: layer, uniquename: APP }];
- if (logical === 'appmodulecomponent') return [{ objectid: '00000000-0000-4000-8000-00000000dddd', componenttype: 62 }];
- if (logical === 'sitemap') return [{ sitemapxml: xml }];
- return [];
- },
- fetchEntityMetadata: async (logical) => ({ schemaName: logical, displayName: 'Ticket', primaryNameAttribute: 'new_subject' }),
- }, { appId, layerId: layer, sitemapXml: xml });
- const source = 'export default function Page(){return null;}';
- const genpage = fakeGenpage({ pages: [{ pageId: pid, name: 'Page', source }] });
- let staged;
- const run = () => download(wire, out, ['--include-managed', '--managed-manifest', storeFileOf(dir)], {
- // The real page download, over a page backend; the restore input is the flow this wire built.
- runDownload: async (args) => {
- const real = await runDownload({ ...args, sdk: pageSdk, genpage });
- assert.equal(real.ok, true, JSON.stringify(real));
- staged = args.stagePages;
- return { ...real, spec: specWith([]) };
- },
- });
- const stagingLeft = () => fs.readdirSync(out).filter((n) => n.startsWith('.download-pages.'));
{
const before = snapshotTree(out);
const failed = await run();
@@ -1092,7 +1100,7 @@ test('a fragments file that cannot be written leaves every output that was there
assert.equal(fs.readFileSync(path.join(out, 'app-spec.json'), 'utf8'), oldSpec);
assert.match(failed.emitted[0].payload.error, /No other output was written\.$/);
assert.deepEqual(stagingLeft(), [], 'the staging folder is removed');
- assert.equal(staged, true, 'the managed download stages its pages');
+ assert.equal(staged(), true, 'the managed download stages its pages');
assert.deepEqual(snapshotTree(out), before, 'no baseline, no fragments, no leftover name: the app folder is exactly as it was');
}
fs.unlinkSync(ws);
@@ -1106,6 +1114,31 @@ test('a fragments file that cannot be written leaves every output that was there
});
});
+for (const [what, plant, refusal] of [
+ ['read-only', (file) => fs.chmodSync(file, 0o444), (e) => e.code === 'IO_ERROR' && e.reason === 'read-only'],
+ ['a hard link', (file, elsewhere) => fs.linkSync(file, path.join(elsewhere, 'twin.json')), (e) => e.code === 'UNSAFE_OUTPUT' && e.reason === 'hard-link'],
+]) {
+ test(`a managed download whose app-spec.json is ${what} is refused before the fragments file or pages/ is written: the app folder is exactly as it was`, async () => {
+ await withBpf(true, async () => {
+ const { out, pageFile, oldSpec, run, stagingLeft, staged } = await managedPagesFixture();
+ const specFile = path.join(out, 'app-spec.json');
+ const elsewhere = makeTempDir('declared-bpf-');
+ plant(specFile, elsewhere);
+ try {
+ const before = snapshotTree(out);
+ await assert.rejects(run(), (e) => refusal(e) && /^refusing to write .*app-spec\.json: .* The download stopped before replacing anything: /.test(e.message));
+ assert.equal(staged(), true, 'the managed download stages its pages');
+ assert.equal(fs.readFileSync(pageFile, 'utf8'), 'MAKER EDIT THAT MUST SURVIVE FAILURE');
+ assert.equal(fs.readFileSync(specFile, 'utf8'), oldSpec);
+ assert.deepEqual(stagingLeft(), [], 'the staging folder is removed');
+ assert.deepEqual(snapshotTree(out), before, 'no fragments, no baseline, no new pages, no leftover name: the app folder is exactly as it was');
+ } finally {
+ fs.chmodSync(specFile, 0o666);
+ }
+ });
+ });
+}
+
test('the fragments file is made by an exclusive create under a new name: a name that is taken, even at the last moment, is left as it is and another is used', () => {
const { settleFragments } = require('../lib/managed-fragments.js');
diff --git a/plugins/model-apps/scripts/tests/sdk-build-declared-forms.test.js b/plugins/model-apps/scripts/tests/sdk-build-declared-forms.test.js
index 41bb4bbcd..bd1c3cccc 100644
--- a/plugins/model-apps/scripts/tests/sdk-build-declared-forms.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-build-declared-forms.test.js
@@ -961,6 +961,53 @@ test('the explicit managed download refuses a handler library it cannot prove is
});
});
+// A download that cannot replace app-spec.json must say so before it writes anything else. With no generative pages there is no page
+// tree to check, so the managed download's pending fragments file is the first thing it could write; it is written only once the spec is known to be replaceable.
+test('a managed download with no generative pages refuses a spec it cannot replace before it writes its fragments file, and a plain one writes nothing before its spec', async () => {
+ await withForms(true, async () => {
+ const org = createFakeBuildOrg({ entities: ENTITIES });
+ const dir = newDir();
+ assert.equal((await build(org, dir, handledSpec(), { phases: ['web-resources', 'forms'] })).err, undefined);
+ // A managed library leaves its form ready to paste: a pending fragment, so the managed download has a fragments file to write.
+ libraryRow(org).ismanaged = true;
+ const flags = ['--include-managed', '--managed-manifest', storeFileOf(org, dir)];
+ const tree = (root) => fs.readdirSync(root, { recursive: true }).sort().map((n) => {
+ const file = path.join(root, n);
+ return fs.lstatSync(file).isDirectory() ? `${n}/` : `${n}=${fs.readFileSync(file, 'utf8')}`;
+ });
+ // Another name for the maker's spec: replacing it would break that link, which the download refuses.
+ const linked = () => {
+ const out = newDir();
+ fs.writeFileSync(path.join(out, 'app-spec.json'), '{"maker":true}');
+ fs.linkSync(path.join(out, 'app-spec.json'), path.join(newDir(), 'spec-twin.json'));
+ return out;
+ };
+
+ const managedOut = linked();
+ const before = tree(managedOut);
+ await assert.rejects(download(org, managedOut, flags), (e) => {
+ assert.deepEqual(tree(managedOut), before, 'no fragments file, no baseline, and the maker\'s spec as it was');
+ assert.equal(e.code, 'UNSAFE_OUTPUT');
+ assert.equal(e.reason, 'hard-link');
+ assert.match(e.message, /The download stopped before replacing anything:/);
+ return true;
+ });
+
+ const plainOut = linked();
+ const plainBefore = tree(plainOut);
+ await assert.rejects(download(org, plainOut, []), (e) => e.code === 'UNSAFE_OUTPUT' && e.reason === 'hard-link' && !/The download stopped before replacing anything/.test(e.message));
+ assert.deepEqual(tree(plainOut), plainBefore, 'the plain download\'s spec write is its first write');
+
+ // The same download over a spec it can replace still writes the fragments file and the spec.
+ const writable = newDir();
+ fs.writeFileSync(path.join(writable, 'app-spec.json'), '{"maker":true}');
+ const ok = await download(org, writable, flags);
+ assert.equal(ok.emitted[0].ok, true, JSON.stringify(ok.emitted) + ok.said);
+ assert.ok(fs.existsSync(ok.emitted[0].payload.managedFragments.file));
+ assert.deepEqual(ok.written.forms, [], 'the form is left to its fragment');
+ });
+});
+
test('the explicit managed download restores a proved declared form from the named binding store, and names any it cannot restore', async () => {
await withForms(true, async () => {
const org = createFakeBuildOrg({ entities: ENTITIES });
diff --git a/plugins/model-apps/scripts/tests/sdk-build.test.js b/plugins/model-apps/scripts/tests/sdk-build.test.js
index bc611e503..ec96435da 100644
--- a/plugins/model-apps/scripts/tests/sdk-build.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-build.test.js
@@ -8,6 +8,7 @@ const { commandDef, chartDef, runSdkBuild: runSdkBuildWithRealWaits, planFor, re
const { validateAppSpec } = require('../lib/app-spec.js');
const { makeTempDir } = require('./helpers/temp-dirs.js');
const { withPageType } = require('./helpers/page-component-type.js');
+const { RETRY } = require('../lib/retry-policy.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.
@@ -192,6 +193,12 @@ function mockSdk(opts = {}) {
const smId = (filter.match(/sitemapid eq (\S+)/) || [])[1];
if (smId === SELF_SITEMAP_ID) return [{ sitemapxml: opts.liveSitemapXml || EMPTY_SITEMAP_XML }];
const idx = Number(String(smId).replace('sm-', '')) - 2;
+ // `readPlan`: what each of the app's published sitemap reads does, in order — 'ok' answers, 'fail' throws (a 5xx while another build changes the app), and a
+ // function is called with the app (to change what it holds from then on) and throws. Reads past the plan answer.
+ const planned = opts.otherApps && opts.otherApps[idx] && opts.otherApps[idx].readPlan;
+ const step = planned && planned.shift();
+ if (step === 'fail') throw new Error('sitemap read failed');
+ if (typeof step === 'function') { step(opts.otherApps[idx]); throw new Error('sitemap read failed'); }
return [{ sitemapxml: (opts.otherApps && opts.otherApps[idx] && opts.otherApps[idx].sitemapxml) || '<SiteMap/>' }];
}
// systemform queries come from THREE build paths, distinguished by their filter:
@@ -7656,7 +7663,8 @@ test('pages: another app\'s saved navigation that cannot be read HALTS pages-sha
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'] }),
+ // The waits before the scans again of an unreadable app are not taken here (`sleep`): what is read again is pinned by the tests after the never-published ones.
+ runSdkBuild(spec, { sdk, apply: true, env: 'https://x', appDir, genpageCli, phases: ['solution', 'data-model', 'app-shell', 'pages'], sleep: async () => {} }),
(e) => {
assert.strictEqual(e.phase, 'pages', what);
assert.strictEqual(e.code, 'pages-shared-check-failed', what);
@@ -7827,10 +7835,13 @@ test('pages: a never-published app whose navigation cannot be read HALTS pages-s
'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 }] },
};
+ // The scan is taken again three times before each halt (`waits`), except the cut-short XML: a stored sitemap that is malformed only changes when someone edits that app.
+ const waits = { 'its sitemap component read fails': [5000, 10000, 20000], 'its saved row did not come back': [5000, 10000, 20000], 'its saved XML is cut short': [] };
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] });
+ const sleeps = [];
await assert.rejects(
- runPagesUpdate(s, sdk),
+ runPagesUpdate(s, sdk, { sleep: async (ms) => { sleeps.push(ms); } }),
(e) => {
assert.strictEqual(e.code, 'pages-shared-check-failed', what);
assert.match(e.message, /1 app\(s\) had an unreadable sitemap \(contoso_draftapp\)/, what);
@@ -7838,11 +7849,172 @@ test('pages: a never-published app whose navigation cannot be read HALTS pages-s
},
what
);
+ assert.deepStrictEqual(sleeps, waits[what], what);
}
assert.deepStrictEqual(s.uploads, []);
} finally { fs.rmSync(s.appDir, { recursive: true, force: true }); }
});
+// Another app's navigation that cannot be read for a moment — while another build or maker changes that app — halted the build, and the same build run minutes later passed.
+// The scan that halts is taken again WHOLE — every app read afresh — after 5 s, 10 s and 20 s; one still unreadable halts as before, and one that is read and holds the page halts as shared.
+const OTHER_PAGE_SITEMAP = '<SiteMap><Area><Group><SubArea GenPageId="00000000-0000-4000-8000-0000000000aa" Title="Other"/></Group></Area></SiteMap>';
+const UNREADABLE_HALT = 'cannot verify pages are not shared across apps — 1 app(s) had an unreadable sitemap (contoso_secondapp); one of them could share a page we are about to UPDATE. Fix or remove the unreadable app(s), then rebuild.';
+// What `more` has that `base` has not, by request, as a multiset; and asserts `base` has nothing `more` has not.
+const extraRequests = (more, base) => {
+ const key = (c) => JSON.stringify([c.name, c.args]);
+ const left = more.map(key);
+ for (const k of base.map(key)) {
+ const i = left.indexOf(k);
+ assert.ok(i >= 0, `a request of the steady run was not sent: ${k}`);
+ left.splice(i, 1);
+ }
+ return left.map((k) => JSON.parse(k));
+};
+const shortRequest = ([name, [first, o]]) => (name === 'queryRecords' ? `${first} ${(o && o.filter) || '(all)'}` : first);
+// `onSleep` is what happens in the environment during each wait: another maker or build at work on another app.
+const updateWithOtherApps = async (s, otherApps, { onSleep = () => {} } = {}) => {
+ const sleeps = [];
+ const { sdk, calls } = mockSdk({ pageManifest: s.existing, manifestId: 'wr-manifest', selfAppUnique: s.appUnique, liveSitemapXml: s.sitemapWithO, otherApps });
+ let halt = null;
+ try { await runPagesUpdate(s, sdk, { sleep: async (ms) => { sleeps.push(ms); onSleep(sleeps.length); } }); } catch (e) { halt = e; }
+ return { calls, sleeps, halt };
+};
+
+test('pages: another app whose sitemap read fails for a moment makes the scan run again WHOLE — every app afresh — and the update goes ahead; the requests are today\'s plus one whole scan', async () => {
+ const s = stageUpdate();
+ try {
+ const apps = (readPlan) => [{ uniquename: 'contoso_secondapp', sitemapxml: OTHER_PAGE_SITEMAP, readPlan }, { uniquename: 'contoso_thirdapp', sitemapxml: OTHER_PAGE_SITEMAP }];
+ const steady = await updateWithOtherApps(s, apps([]));
+ assert.strictEqual(steady.halt, null);
+ assert.deepStrictEqual(steady.sleeps, [], 'nothing unreadable: no wait');
+ const flaky = await updateWithOtherApps(s, apps(['fail']));
+ assert.strictEqual(flaky.halt, null, `the build goes ahead: ${flaky.halt && flaky.halt.message}`);
+ assert.deepStrictEqual(flaky.sleeps, [5000], 'one wait, then the scan again, which reads every app');
+ assert.deepStrictEqual(s.uploads.map((u) => u.pageId), [GP_O, GP_O], 'the page is updated in place in both builds');
+ // The scan again is the WHOLE scan: the two lists the apps are found in, EVERY other app's three reads (the one read before the wait too), and the saved layer.
+ assert.deepStrictEqual(extraRequests(flaky.calls, steady.calls).map(shortRequest).sort(), [
+ APPS_LIST_URL,
+ SAVED_URL,
+ 'appmodule (all)',
+ 'appmodule uniquename eq \'contoso_secondapp\'',
+ 'appmodulecomponent _appmoduleidunique_value eq uv-2 and componenttype eq 62',
+ 'sitemap sitemapid eq sm-2',
+ 'appmodule uniquename eq \'contoso_thirdapp\'',
+ 'appmodulecomponent _appmoduleidunique_value eq uv-3 and componenttype eq 62',
+ 'sitemap sitemapid eq sm-3',
+ ].sort());
+ } finally { fs.rmSync(s.appDir, { recursive: true, force: true }); }
+});
+
+test('pages: another app whose sitemap read fails every time makes the scan run again three times, then HALTS pages-shared-check-failed exactly as before; a malformed one is not waited for', async () => {
+ const s = stageUpdate();
+ try {
+ const cases = {
+ 'every read fails': [{ uniquename: 'contoso_secondapp', sitemapxml: OTHER_PAGE_SITEMAP, readPlan: ['fail', 'fail', 'fail', 'fail', 'ok'] }, [5000, 10000, 20000]],
+ 'its stored sitemap is malformed': [{ uniquename: 'contoso_secondapp', sitemapxml: '<SiteMap><Area' }, []],
+ };
+ for (const [what, [app, waits]] of Object.entries(cases)) {
+ const { sleeps, halt } = await updateWithOtherApps(s, [app]);
+ assert.ok(halt, what);
+ assert.deepStrictEqual({ phase: halt.phase, code: halt.code, recoverable: halt.recoverable, retry: halt.retry, message: halt.message },
+ { phase: 'pages', code: 'pages-shared-check-failed', recoverable: true, retry: RETRY.NEVER, message: UNREADABLE_HALT }, what);
+ assert.deepStrictEqual(sleeps, waits, what);
+ if (app.readPlan) assert.deepStrictEqual(app.readPlan, ['ok'], `${what}: the first scan and three more, no more`);
+ }
+ assert.deepStrictEqual(s.uploads, [], 'nothing was uploaded while sharing could not be ruled out');
+ } finally { fs.rmSync(s.appDir, { recursive: true, force: true }); }
+});
+
+test('pages: another app read on a scan again that HOLDS the page halts pages-shared-across-apps — before any write, and right before the first write in place', async () => {
+ const s = stageUpdate();
+ try {
+ // Before any write: its first read fails, and the scan again finds the page.
+ const before = await updateWithOtherApps(s, [{ uniquename: 'contoso_secondapp', sitemapxml: s.sitemapWithO, readPlan: ['fail'] }]);
+ assert.ok(before.halt);
+ assert.strictEqual(before.halt.code, 'pages-shared-across-apps');
+ assert.match(before.halt.message, new RegExp(`^generative page\\(s\\) shared across apps: ${GP_O} \\(also in contoso_secondapp\\)`));
+ assert.deepStrictEqual(before.sleeps, [5000]);
+ // The scan right before the first write in place: the first scan reads the app, the second cannot, and by the scan again the app holds the page.
+ const during = await updateWithOtherApps(s, [{ uniquename: 'contoso_secondapp', sitemapxml: OTHER_PAGE_SITEMAP, readPlan: ['ok', (app) => { app.sitemapxml = s.sitemapWithO; }] }]);
+ assert.ok(during.halt);
+ assert.strictEqual(during.halt.code, 'pages-shared-across-apps');
+ assert.match(during.halt.message, new RegExp(`^generative page\\(s\\) became shared across apps while this build ran: ${GP_O} \\(also in contoso_secondapp\\)`));
+ assert.deepStrictEqual(during.sleeps, [5000]);
+ assert.deepStrictEqual(s.uploads, [], 'the shared page was never uploaded');
+ } finally { fs.rmSync(s.appDir, { recursive: true, force: true }); }
+});
+
+test('pages: the scan right before the first write in place runs again too — the build goes ahead when the app is read, and halts exactly as before when it never is', async () => {
+ const s = stageUpdate();
+ try {
+ const passes = await updateWithOtherApps(s, [{ uniquename: 'contoso_secondapp', sitemapxml: OTHER_PAGE_SITEMAP, readPlan: ['ok', 'fail'] }]);
+ assert.strictEqual(passes.halt, null, `the build goes ahead: ${passes.halt && passes.halt.message}`);
+ assert.deepStrictEqual(passes.sleeps, [5000]);
+ assert.deepStrictEqual(s.uploads.map((u) => u.pageId), [GP_O]);
+ s.uploads.length = 0;
+ const app = { uniquename: 'contoso_secondapp', sitemapxml: OTHER_PAGE_SITEMAP, readPlan: ['ok', 'fail', 'fail', 'fail', 'fail', 'ok'] };
+ const halts = await updateWithOtherApps(s, [app]);
+ assert.ok(halts.halt);
+ assert.deepStrictEqual({ phase: halts.halt.phase, code: halts.halt.code, recoverable: halts.halt.recoverable, retry: halts.halt.retry, message: halts.halt.message },
+ { phase: 'pages', code: 'pages-shared-check-failed', recoverable: true, retry: RETRY.NEVER, message: UNREADABLE_HALT });
+ assert.deepStrictEqual(halts.sleeps, [5000, 10000, 20000]);
+ assert.deepStrictEqual(app.readPlan, ['ok'], 'the read of each scan and three scans again, no more');
+ assert.deepStrictEqual(s.uploads, []);
+ } finally { fs.rmSync(s.appDir, { recursive: true, force: true }); }
+});
+
+// An app the scan COULD read before a wait may take the page in during it. Merging the apps read again into the answers from before the wait let the scan right before the
+// first write in place pass on a stale answer for that app, and the page was written though another app now held it. The scan again reads every app, so it halts.
+test('pages: another app that was readable and takes the page in DURING the wait for an unreadable one halts pages-shared-across-apps — before any write, and right before the first write in place; nothing is uploaded', async () => {
+ const s = stageUpdate();
+ try {
+ const takesThePage = (apps) => () => { Object.assign(apps[1], { sitemapxml: s.sitemapWithO, savedSitemapXml: s.sitemapWithO }); };
+ const cases = {
+ 'before any write': [['fail'], /^generative page\(s\) shared across apps: /],
+ 'right before the first write in place': [['ok', 'fail'], /^generative page\(s\) became shared across apps while this build ran: /],
+ };
+ for (const [what, [readPlan, words]] of Object.entries(cases)) {
+ const apps = [{ uniquename: 'contoso_secondapp', sitemapxml: OTHER_PAGE_SITEMAP, readPlan }, { uniquename: 'contoso_thirdapp', sitemapxml: OTHER_PAGE_SITEMAP }];
+ const out = await updateWithOtherApps(s, apps, { onSleep: takesThePage(apps) });
+ assert.ok(out.halt, `${what}: the build must not go ahead`);
+ assert.strictEqual(out.halt.code, 'pages-shared-across-apps', `${what}: ${out.halt.message}`);
+ assert.match(out.halt.message, words, what);
+ assert.match(out.halt.message, new RegExp(`${GP_O} \\(also in contoso_thirdapp\\)`), what);
+ assert.deepStrictEqual(out.sleeps, [5000], what);
+ assert.deepStrictEqual(s.uploads, [], `${what}: the page another app now holds is never uploaded`);
+ }
+ } finally { fs.rmSync(s.appDir, { recursive: true, force: true }); }
+});
+
+// A scan that fails AS A WHOLE after a wait is not an answer: it is waited out like an unreadable app, and the last one halts as a failed scan (retried by its cause, as a
+// first scan that fails is) — never on the answers of an older scan.
+test('pages: a scan again that fails as a whole is waited out; the last one halts pages-shared-check-failed as a failed scan, and nothing is uploaded', async () => {
+ const s = stageUpdate();
+ try {
+ const failingLists = (from) => {
+ const { sdk } = mockSdk({ pageManifest: s.existing, manifestId: 'wr-manifest', selfAppUnique: s.appUnique, liveSitemapXml: s.sitemapWithO,
+ otherApps: [{ uniquename: 'contoso_secondapp', sitemapxml: OTHER_PAGE_SITEMAP, readPlan: ['fail'] }] });
+ const query = sdk.queryRecords;
+ let lists = 0;
+ sdk.queryRecords = async (entity, o) => {
+ if (entity === 'appmodule' && !(o && o.filter) && ++lists >= from) throw new Error('appmodule list failed');
+ return query.call(sdk, entity, o);
+ };
+ return { sdk };
+ };
+ // The lists fail from the first scan again on: three waits, and the halt of a scan that failed.
+ const { sdk } = failingLists(2);
+ const sleeps = [];
+ let halt = null;
+ try { await runPagesUpdate(s, sdk, { sleep: async (ms) => { sleeps.push(ms); } }); } catch (e) { halt = e; }
+ assert.ok(halt);
+ assert.strictEqual(halt.code, 'pages-shared-check-failed');
+ assert.match(halt.message, /^could not scan the environment for pages shared across apps \(appmodule list failed\)/);
+ assert.deepStrictEqual(sleeps, [5000, 10000, 20000]);
+ 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 () => {
// The unit tests pin reportPartialPush; this pins that the ENGINE is wired to it. Before the fix a
// build in which every publish failed reported ok:true with zero warnings and zero error events —
diff --git a/plugins/model-apps/scripts/tests/sitemap-pages.test.js b/plugins/model-apps/scripts/tests/sitemap-pages.test.js
index ab2a6ef94..f3f96bf86 100644
--- a/plugins/model-apps/scripts/tests/sitemap-pages.test.js
+++ b/plugins/model-apps/scripts/tests/sitemap-pages.test.js
@@ -1,7 +1,7 @@
'use strict';
const { test } = require('node:test');
const assert = require('node:assert');
-const { sitemapGenPages, sitemapGenPageIds, navigationGenPageIds, liveNavEntries, fetchSitemap, fetchAppsForPages, decodeXmlEntities, appNavigationMatchesSitemap, navigationProof } = require('../lib/sitemap-pages.js');
+const { sitemapGenPages, sitemapGenPageIds, navigationGenPageIds, liveNavEntries, fetchSitemap, fetchAppsForPages, rescanWhileUnreadable, decodeXmlEntities, appNavigationMatchesSitemap, navigationProof } = require('../lib/sitemap-pages.js');
const GP_OVERVIEW = '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8';
const GP_DETAIL = '5c0a4889-45fd-46ea-91a8-ff876914d644';
@@ -444,6 +444,92 @@ function scanEnv(apps, { drafts = [], savedPages, appList, noDataverse } = {}) {
return { sdk, calls };
}
+// A build halted when another app was unreadable for a moment (another build was changing it), and passed when run again minutes later. The scan is taken again WHOLE —
+// every app read afresh — before the caller gives up on such an app, and the answer is the last complete scan, so no app's answer is older than the wait.
+const appListRows = (apps) => ({ status: 200, body: { value: apps.map((a, i) => ({ appmoduleid: `app-${i}`, appmoduleidunique: layerKey(i), uniquename: a.name, componentstate: 0 })) } });
+
+test('rescanWhileUnreadable: takes the whole scan again after each wait, every app afresh; a scan that fails as a whole is waited out; an app that took the page in DURING a wait is in the answer', async () => {
+ const apps = [
+ { name: 'app-a', published: withPage() },
+ { name: 'app-b', published: '' }, // no XML yet: unreadable for now (sitemap-xml-unreadable)
+ { name: 'app-c', published: withPage(GP_DETAIL) }, // readable, and clear of the page, before the waits
+ ];
+ let listReads = 0;
+ // The second read of the list of apps fails, so the first scan again fails as a whole.
+ const appList = () => (++listReads === 2 ? { status: 503, body: null } : appListRows(apps));
+ const { sdk, calls } = scanEnv(apps, { appList });
+ const marks = [];
+ const sleeps = [];
+ const sleep = async (ms) => {
+ sleeps.push(ms);
+ marks.push(calls.queries.length);
+ // By the second wait the other build has published app-b; and a maker has put the page into app-c, which the first scan read as clear of it.
+ if (sleeps.length === 2) {
+ apps[1].published = withPage(GP_DETAIL);
+ Object.assign(apps[2], { published: withPage(GP_DETAIL), saved: withPage(GP_DETAIL, GP_OVERVIEW) });
+ }
+ };
+ const r = await rescanWhileUnreadable(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-a' }, { sleep });
+ assert.strictEqual(r.ok, true);
+ assert.deepStrictEqual(sleeps, [5000, 10000], 'the scan that failed as a whole is followed by another; the one that reads every app ends the waits');
+ assert.deepStrictEqual(r.unreadable, []);
+ assert.deepStrictEqual(r.byId.get(GP_OVERVIEW), ['app-c'], 'the app that took the page in during the wait holds it in the answer: the caller halts as shared');
+ assert.deepStrictEqual(r.savedOnly.get(GP_OVERVIEW), ['app-c']);
+ // The last scan sends every request the first one did: every app is read again, not only the one that was unreadable.
+ const firstScan = calls.queries.slice(0, marks[0]);
+ const lastScan = calls.queries.slice(marks[1]);
+ assert.deepStrictEqual(lastScan.slice().sort(), firstScan.slice().sort());
+ assert.strictEqual(lastScan.filter((e) => e === 'sitemap').length, 2, 'both other apps\' sitemaps are read again, the one read before the wait too');
+});
+
+test('rescanWhileUnreadable: the last scan is the answer — still unreadable, or failed as a whole — and a first scan with nothing to wait for is answered as it came, with no request beyond it', async () => {
+ const sleepsOf = () => { const sleeps = []; return { sleeps, sleep: async (ms) => { sleeps.push(ms); } }; };
+ // Unreadable through every wait: three more scans, and the last one names the app.
+ {
+ const { sdk } = scanEnv([{ name: 'app-a', published: withPage() }, { name: 'app-b', published: '' }]);
+ const { sleeps, sleep } = sleepsOf();
+ const r = await rescanWhileUnreadable(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-a' }, { sleep });
+ assert.deepStrictEqual(sleeps, [5000, 10000, 20000]);
+ assert.strictEqual(r.ok, true);
+ assert.deepStrictEqual(r.unreadable, ['app-b']);
+ }
+ // Every scan after the first fails as a whole: the answer is the failed last one, never the older answers of the first.
+ {
+ const apps = [{ name: 'app-a', published: withPage() }, { name: 'app-b', published: '' }];
+ let listReads = 0;
+ const { sdk } = scanEnv(apps, { appList: () => (++listReads >= 2 ? { status: 503, body: null } : appListRows(apps)) });
+ const { sleeps, sleep } = sleepsOf();
+ const r = await rescanWhileUnreadable(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-a' }, { sleep });
+ assert.deepStrictEqual(sleeps, [5000, 10000, 20000]);
+ assert.strictEqual(r.ok, false);
+ assert.match(r.error, /^could not /);
+ }
+ // Answered as it came, with no wait and exactly the requests of one scan: nothing unreadable; only malformed apps (only an edit of the app changes them); a first scan
+ // that failed as a whole.
+ const cases = {
+ 'nothing unreadable': [{ name: 'app-a', published: withPage() }, { name: 'app-b', published: withPage(GP_DETAIL) }],
+ 'only a malformed app': [{ name: 'app-a', published: withPage() }, { name: 'app-b', published: '<SiteMap><Area' }] /* cut off mid-tag */,
+ };
+ for (const [what, apps] of Object.entries(cases)) {
+ const once = scanEnv(apps);
+ const expected = await fetchAppsForPages(once.sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-a' });
+ const { sdk, calls } = scanEnv(apps);
+ const { sleeps, sleep } = sleepsOf();
+ const r = await rescanWhileUnreadable(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-a' }, { sleep });
+ assert.deepStrictEqual(sleeps, [], what);
+ assert.deepStrictEqual(r, expected, what);
+ assert.deepStrictEqual(calls.queries, once.calls.queries, what);
+ if (what === 'only a malformed app') assert.strictEqual(r.unreadableReasons.get('app-b'), 'malformed');
+ }
+ {
+ const apps = [{ name: 'app-a', published: withPage() }, { name: 'app-b', published: '' }];
+ const { sdk } = scanEnv(apps, { appList: () => ({ status: 503, body: null }) });
+ const { sleeps, sleep } = sleepsOf();
+ const r = await rescanWhileUnreadable(sdk, [GP_OVERVIEW], { excludeAppUnique: 'app-a' }, { sleep });
+ assert.deepStrictEqual(sleeps, [], 'a first scan that failed as a whole: the caller halts on it, with the retry its cause earns');
+ assert.strictEqual(r.ok, false);
+ }
+});
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() },
diff --git a/plugins/model-apps/scripts/tests/verify-spec.test.js b/plugins/model-apps/scripts/tests/verify-spec.test.js
index d6e267022..f85723778 100644
--- a/plugins/model-apps/scripts/tests/verify-spec.test.js
+++ b/plugins/model-apps/scripts/tests/verify-spec.test.js
@@ -3879,4 +3879,163 @@ test('readManagedManifest: read-only; no store and a non-https target are empty,
assert.deepStrictEqual(broken.invalid.map((i) => [i.family, i.key, i.code]), [['store', 'managed-bindings', 'managed-binding-store-unreadable']]);
assert.strictEqual(fs.readFileSync(file, 'utf8'), '{ "not": "a store"');
assert.notStrictEqual(bytes, '');
+});
+// CHART CONTENT (lib/chart-verify.js). The deployed row a chart's checks read: the SDK's own scratch datadescription and presentation
+// (ChartAdapter in scripts/vendor/cds-maker-sdk.cjs), with the parts each test varies.
+const chartData = ({ entity = 'new_o', group = 'new_status', agg = 'count', measureOn, inner = '', extraAttrs = '', categories } = {}) => '<datadefinition><fetchcollection>'
+ + `<fetch mapping="logical" aggregate="true"><entity name="${entity}"><attribute alias="agg_0" name="${measureOn || `${entity}id`}" aggregate="${agg}" />`
+ + `<attribute alias="grp_0" name="${group}" groupby="true"${extraAttrs} />${inner}</entity></fetch></fetchcollection>`
+ + `<categorycollection>${categories || '<category alias="grp_0"><measurecollection><measure alias="agg_0" /></measurecollection></category>'}</categorycollection></datadefinition>`;
+const chartPres = ({ type = 'Column', title, series } = {}) => `<Chart Palette="BrightPastel">${title === undefined ? '' : `<Titles><Title>${title}</Title></Titles>`}`
+ + `<Series>${series || `<Series ChartType="${type}" ChartArea="Default" IsValueShownAsLabel="True" />`}</Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>`;
+const chartRow = (over = {}) => ({ savedqueryvisualizationid: 'c-1', primaryentitytypecode: 'new_o', name: 'C', description: null, datadescription: chartData(), presentationdescription: chartPres(), ...over });
+const chartSpec = (chart) => ({ entities: [], views: [], forms: [], appShell: { areas: [] }, charts: [{ entity: 'new_o', name: 'C', chartType: 'Column', groupBy: 'new_status', ...chart }] });
+// A reader holding the given chart rows; records every chart read so a test can say which row was asked for.
+const chartReader = (rows, reads = []) => ({
+ sitemapXml: async () => '<SiteMap/>',
+ queryRecords: async (set, q) => {
+ reads.push({ set, ...q });
+ if (set !== 'savedqueryvisualization') return [];
+ const byId = /savedqueryvisualizationid eq (\S+)/.exec(q.filter || '');
+ return byId ? rows.filter((r) => r.savedqueryvisualizationid === byId[1]) : rows;
+ },
+});
+const chartChecks = (r) => r.checks.filter((c) => c.kind.startsWith('chart'));
+
+test('verifySpec charts: a present chart of another type, grouping or aggregate fails; the one the spec describes passes', async () => {
+ for (const declared of [false, true]) {
+ const extra = declared ? { reconcile: 'declared' } : {};
+ const good = await verifySpec(chartSpec(extra), chartReader([chartRow()]));
+ assert.strictEqual(good.ok, true, JSON.stringify(good.missing));
+ assert.deepStrictEqual(chartChecks(good).map((c) => [c.kind, c.present]), [['chart', true], ['chart-type', true], ['chart-data', true]]);
+ const cases = [
+ [{ presentationdescription: chartPres({ type: 'Pie' }) }, 'chart-type', /it is a Pie chart, not Column/],
+ [{ datadescription: chartData({ group: 'new_priority' }) }, 'chart-data', /groups by new_priority, not new_status/],
+ [{ datadescription: chartData({ agg: 'countcolumn' }) }, 'chart-data', /aggregates with countcolumn, not count/],
+ ];
+ for (const [over, kind, detail] of cases) {
+ const r = await verifySpec(chartSpec(extra), chartReader([chartRow(over)]));
+ assert.strictEqual(r.ok, false, `${kind} ${declared}`);
+ const miss = r.missing.find((m) => m.kind === kind);
+ assert.ok(miss && detail.test(miss.detail), JSON.stringify(r.missing));
+ assert.strictEqual(/not reconcile: "declared"/.test(miss.detail), !declared, 'a legacy chart says why a rebuild leaves it');
+ assert.ok(r.checks.some((c) => c.kind === 'chart' && c.present), 'the chart itself is present');
+ }
+ }
+});
+
+test('verifySpec charts: a filter, a join, a date grouping, a second measure, series or category are failures; another table too', async () => {
+ const twoMeasures = chartData({ inner: '<attribute alias="agg_1" name="new_oid" aggregate="count" />' });
+ const cases = [
+ [chartData({ inner: '<filter><condition attribute="statecode" operator="eq" value="0" /></filter>' }), /a filter narrows/],
+ [chartData({ inner: '<link-entity name="account" from="accountid" to="new_account" link-type="inner" />' }), /joins account/],
+ [chartData({ extraAttrs: ' dategrouping="month"' }), /by month/],
+ [twoMeasures, /2 measures/],
+ [chartData({ categories: '<category alias="grp_0"><measurecollection><measure alias="agg_0" /><measure alias="agg_0" /></measurecollection></category>' }), /2 series/],
+ [chartData({ categories: '<category alias="grp_0"><measurecollection><measure alias="agg_0" /></measurecollection></category><category alias="grp_0"><measurecollection><measure alias="agg_0" /></measurecollection></category>' }), /2 categories/],
+ [chartData({ entity: 'new_p', measureOn: 'new_oid' }), /reads new_p, not new_o/],
+ ];
+ for (const [datadescription, detail] of cases) {
+ const r = await verifySpec(chartSpec({ reconcile: 'declared' }), chartReader([chartRow({ datadescription })]));
+ const miss = r.missing.find((m) => m.kind === 'chart-data');
+ assert.ok(miss && detail.test(miss.detail), `${detail}: ${JSON.stringify(r.missing)} ${JSON.stringify(r.unverified)}`);
+ }
+});
+
+test('verifySpec charts: formatting, aliases and styling do not matter; what the verifier does not model is unverified, never a pass or a failure', async () => {
+ // An XML declaration, single quotes, another attribute order, an explicit end tag, white space, other aliases, a custom palette.
+ const reformatted = "<?xml version='1.0' encoding='utf-8'?>\n<datadefinition>\n <fetchcollection>\n <fetch aggregate='true' mapping='logical'>\n"
+ + " <entity name='new_o'>\n <attribute groupby='true' name='new_status' alias='g'></attribute>\n <attribute aggregate='count' name='new_oid' alias='m'/>\n"
+ + " </entity>\n </fetch>\n </fetchcollection>\n <categorycollection><category alias='g'><measurecollection><measure alias='m'/></measurecollection></category></categorycollection>\n</datadefinition>";
+ const styled = "<Chart Palette='None' PaletteCustomColors='55,118,193'><Series><Series ChartArea='Default' ChartType='column' CustomProperties='PointWidth=0.75'></Series></Series><ChartAreas /></Chart>";
+ const ok = await verifySpec(chartSpec({ reconcile: 'declared' }), chartReader([chartRow({ datadescription: reformatted, presentationdescription: styled })]));
+ assert.strictEqual(ok.ok, true, JSON.stringify(ok.missing));
+ assert.strictEqual(ok.unverified, undefined);
+ assert.deepStrictEqual(chartChecks(ok).map((c) => [c.kind, c.present]), [['chart', true], ['chart-type', true], ['chart-data', true]]);
+ const unknown = [
+ [{ datadescription: chartData({ inner: '<order alias="grp_0" descending="false" />' }) }, /chart-data:C \(.*an order on its groups/],
+ [{ datadescription: chartData({ inner: '<link-entity name="account" from="accountid" to="new_account" link-type="outer" />' }) }, /chart-data:C \(.*an outer join/],
+ [{ datadescription: chartData({ agg: 'Count' }) }, /chart-data:C \(.*the aggregate "Count"/],
+ [{ datadescription: chartData({ extraAttrs: ' distinct="true"' }) }, /chart-data:C \(.*the attribute distinct/],
+ [{ datadescription: '<!DOCTYPE d [<!ENTITY x "y">]><datadefinition/>' }, /chart-data:C \(its datadescription is not XML the verifier reads/],
+ [{ datadescription: '<datadefinition><fetchcollection>' }, /chart-data:C \(its datadescription is not XML/],
+ [{ datadescription: null }, /chart-data:C \(the chart has no datadescription/],
+ [{ presentationdescription: chartPres({ series: '<Series ChartArea="Default" />' }) }, /chart-type:C \(its series states no chart type/],
+ ];
+ for (const [over, line] of unknown) {
+ const r = await verifySpec(chartSpec({ reconcile: 'declared' }), chartReader([chartRow(over)]));
+ assert.strictEqual(r.ok, true, `${line}: ${JSON.stringify(r.missing)}`);
+ assert.ok(r.unverified.some((u) => line.test(u)), `${line}: ${JSON.stringify(r.unverified)}`);
+ }
+ // A known contradiction is a failure whatever else the document holds.
+ const both = await verifySpec(chartSpec({}), chartReader([chartRow({ datadescription: chartData({ group: 'new_x', inner: '<order alias="grp_0" />' }) })]));
+ assert.ok(both.missing.some((m) => m.kind === 'chart-data' && /groups by new_x/.test(m.detail)));
+ // A legacy measure that is no FetchXML aggregate is not compared.
+ const odd = await verifySpec(chartSpec({ measure: 'Sum' }), chartReader([chartRow()]));
+ assert.strictEqual(odd.ok, true);
+ assert.ok(odd.unverified.some((u) => /^chart-data:C \(.*"Sum" is not an aggregate/.test(u)), JSON.stringify(odd.unverified));
+});
+
+test('verifySpec charts: a declared title and an explicit description are held; a legacy title is not', async () => {
+ const declared = { reconcile: 'declared', title: 'Open by status', description: 'Counts open rows' };
+ const right = await verifySpec(chartSpec(declared), chartReader([chartRow({ description: 'Counts open rows', presentationdescription: chartPres({ title: 'Open by status' }) })]));
+ assert.strictEqual(right.ok, true, JSON.stringify(right.missing));
+ assert.deepStrictEqual(chartChecks(right).map((c) => c.kind), ['chart', 'chart-type', 'chart-data', 'chart-description', 'chart-title']);
+ const noTitle = await verifySpec(chartSpec(declared), chartReader([chartRow({ description: 'Counts open rows' })]));
+ assert.ok(noTitle.missing.some((m) => m.kind === 'chart-title' && /no title element/.test(m.detail)), JSON.stringify(noTitle.missing));
+ const otherTitle = await verifySpec(chartSpec(declared), chartReader([chartRow({ description: 'Counts open rows', presentationdescription: chartPres({ title: 'Open &amp; closed' }) })]));
+ assert.ok(otherTitle.missing.some((m) => m.kind === 'chart-title' && /its title is "Open & closed"/.test(m.detail)));
+ const otherDescription = await verifySpec(chartSpec({ description: 'Counts open rows' }), chartReader([chartRow({ description: 'Something else' })]));
+ assert.ok(otherDescription.missing.some((m) => m.kind === 'chart-description'), JSON.stringify(otherDescription.missing));
+ const legacyTitle = await verifySpec(chartSpec({ title: 'Ignored by the legacy build' }), chartReader([chartRow()]));
+ assert.strictEqual(legacyTitle.ok, true);
+ assert.strictEqual(legacyTitle.checks.some((c) => c.kind === 'chart-title'), false);
+});
+
+test('verifySpec charts: an id-only reader proves presence and names the content unverified; a missing chart stays missing; a namesake pair is present but unverified', async () => {
+ const idOnly = await verifySpec(chartSpec({ reconcile: 'declared', title: 'T' }), { sitemapXml: async () => '<SiteMap/>', queryRecords: async () => [{ savedqueryvisualizationid: 'c-1' }] });
+ assert.strictEqual(idOnly.ok, true, 'content that was not read is unverified, not missing');
+ assert.deepStrictEqual(chartChecks(idOnly).map((c) => [c.kind, c.present]), [['chart', true]]);
+ assert.deepStrictEqual(idOnly.unverified, ['chart-type', 'chart-data', 'chart-title'].map((k) => `${k}:C (the read does not carry the chart\u2019s content)`));
+ // A declared description is still held when the row carries one, with or without the XML columns.
+ const described = (description) => verifySpec(chartSpec({ reconcile: 'declared', description: 'Counts open rows' }), { sitemapXml: async () => '<SiteMap/>', queryRecords: async () => [{ savedqueryvisualizationid: 'c-1', description }] });
+ assert.deepStrictEqual(chartChecks(await described('Counts open rows')).map((c) => [c.kind, c.present]), [['chart', true], ['chart-description', true]]);
+ assert.ok((await described('Something else')).missing.some((m) => m.kind === 'chart-description'));
+ const twoIdOnly = await verifySpec(chartSpec({}), { sitemapXml: async () => '<SiteMap/>', queryRecords: async () => [{ savedqueryvisualizationid: 'c-1' }, { savedqueryvisualizationid: 'c-2' }] });
+ assert.strictEqual(twoIdOnly.ok, true);
+ assert.deepStrictEqual(twoIdOnly.unverified, ['chart-data:C (several charts on new_o have this name, so which one the spec describes is not known)']);
+ const gone = await verifySpec(chartSpec({}), chartReader([]));
+ assert.deepStrictEqual(gone.missing.map((m) => m.kind), ['chart']);
+ const two = await verifySpec(chartSpec({}), chartReader([chartRow(), chartRow({ savedqueryvisualizationid: 'c-2', presentationdescription: chartPres({ type: 'Pie' }) })]));
+ assert.strictEqual(two.ok, true);
+ assert.deepStrictEqual(chartChecks(two).map((c) => c.kind), ['chart']);
+ assert.ok(two.unverified.some((u) => /^chart-data:C \(several charts on new_o have this name/.test(u)));
+ // A row on another table (a reader that did not filter) is not the chart.
+ const elsewhere = await verifySpec(chartSpec({}), chartReader([chartRow({ primaryentitytypecode: 'new_p' })]));
+ assert.deepStrictEqual(elsewhere.missing.map((m) => m.kind), ['chart']);
+});
+
+test('verifySpec charts: a declared chart with a managed binding is its bound row; a namesake is not taken in its place; an open binding is unverified', async () => {
+ const bound = '11111111-2222-4333-8444-555555555555';
+ const manifest = (over = {}) => ({ revision: 1, groups: [{ family: 'chart', key: 'new_o/C', root: { kind: 'chart', key: 'new_o/C', id: bound } }], pending: [], invalid: [], ...over });
+ const reads = [];
+ const r = await verifySpec(chartSpec({ reconcile: 'declared' }), chartReader([chartRow({ savedqueryvisualizationid: bound, name: 'Renamed by a maker' })], reads), { managedManifest: manifest() });
+ assert.strictEqual(r.ok, true, JSON.stringify(r.missing));
+ assert.ok(r.checks.some((c) => c.kind === 'chart-data' && c.present));
+ assert.ok(reads.some((q) => q.filter === `savedqueryvisualizationid eq ${bound}` && q.select.includes('datadescription')));
+ assert.strictEqual(reads.some((q) => /name eq/.test(q.filter || '')), false, 'the name is not asked');
+ const namesake = await verifySpec(chartSpec({ reconcile: 'declared' }), chartReader([chartRow()]), { managedManifest: manifest() });
+ const miss = namesake.missing.find((m) => m.kind === 'chart');
+ assert.ok(miss && /bound to \(11111111-2222-4333-8444-555555555555\) was not found; a chart of the same name is not taken/.test(miss.detail), JSON.stringify(namesake.missing));
+ for (const open of [
+ { pending: [{ family: 'chart', key: 'new_o/C', code: 'managed-settlement-pending' }], groups: [] },
+ { invalid: [{ family: 'store', key: 'managed-bindings', code: 'managed-binding-store-unreadable' }], groups: [] },
+ ]) {
+ const u = await verifySpec(chartSpec({ reconcile: 'declared' }), chartReader([chartRow({ presentationdescription: chartPres({ type: 'Pie' }) })]), { managedManifest: manifest(open) });
+ assert.strictEqual(u.checks.some((c) => c.kind.startsWith('chart')), false, JSON.stringify(u.checks));
+ assert.ok(u.unverified.some((x) => /^chart:C \(its managed binding \(new_o\/C\) is not settled/.test(x)), JSON.stringify(u.unverified));
+ }
+ // A legacy chart is found by its name, whatever the manifest holds.
+ const legacy = await verifySpec(chartSpec({}), chartReader([chartRow()]), { managedManifest: manifest() });
+ assert.ok(legacy.checks.some((c) => c.kind === 'chart' && c.present));
});
\ No newline at end of file
diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.md
index 27084afa6..03ced4b73 100644
--- a/plugins/model-apps/skills/app-builder/SKILL.md
+++ b/plugins/model-apps/skills/app-builder/SKILL.md
@@ -275,7 +275,8 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfaces
layer holds a change made elsewhere. If the stop says that change is not published, tell the maker to
publish it in Maker if it should stay, or undo it and save, then run the build again.
- **Stable create ids** (`minimumPluginVersion: "2.21.0"`) — write `createIdentity: "stable-v1"` on a
- **new** app; never add it to an existing or downloaded spec. Tell the maker: declared views and charts
+ **new** app; never add it to an existing or downloaded spec (a managed download writes it back itself, only
+ with the declared views and charts it restores). Tell the maker: declared views and charts
get ids the spec fixes, so a retry after a lost answer binds the same row instead of creating a second;
configuration items, custom APIs, environment variables, field security, duplicate rules and pages keep
today's ids; and a local copy with an unsent edit stops the build (`create-completion-required`) —
@@ -290,7 +291,8 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfaces
reference is bound to a connection and the Custom API has an implementation (a plug-in type) — a declared
Custom API alone is a scaffold; clearing a value, unbinding a reference or removing a parameter or condition
needs `--authorize <kind>:<key>:<field>` (the refusal names it); a teardown keeps these items and names them;
- a download does not bring them back into the spec yet; and a whole-build retry after a lost answer can create
+ a plain download does not bring them back into the spec (a managed download of a `configurationIdentity:
+ "stable-v1"` app brings back the ones its store proves, never a value, default, connection, implementation or duplicate rule); and a whole-build retry after a lost answer can create
a second row, so check the environment before running a failed build again. See
[`references/app-spec-schema.md`](../../references/app-spec-schema.md) → *Configuration items*.
- **AI-first features** (admin-gated) — form-fill assist, natural-language grid/view search, NL chart
@@ -982,7 +984,11 @@ not everything:**
carrying the deployed view/chart ids), the icon web resources, and the solution.
- **Does NOT round-trip:** `forms[]`, `views[]`, `charts[]`, `commands[]` — they come back empty
(a declared form comes back only with `--include-managed --managed-manifest <store file>`; see
- **Declared form layouts**). `commandStates[]` is never written either: a button's hidden / disabled
+ **Declared form layouts**; so does a declared view a `createIdentity` build created and the store proves
+ unchanged while the app's solution holds it, with its `viewId` and `createIdentity` (a rebuild writes
+ nothing to it; the rest of the rebuild runs as usual), the rest named in `managedViews.omitted`, and such a
+ declared chart, with no id (only a build from the same folder's store binds it), the rest named in
+ `managedCharts.omitted`). `commandStates[]` is never written either: a button's hidden / disabled
state stays on the live row.
All four **survive on the live app** (a rebuild preserves them by discovery), so a plain edit is
safe; they just aren't editable through the downloaded spec. Change them in Maker or a fresh spec.
diff --git a/plugins/model-apps/skills/genpage/SKILL.md b/plugins/model-apps/skills/genpage/SKILL.md
index 127a664c5..bda2bc994 100644
--- a/plugins/model-apps/skills/genpage/SKILL.md
+++ b/plugins/model-apps/skills/genpage/SKILL.md
@@ -83,7 +83,14 @@ application of planned edits.
## Instructions
-Follow these phases in order for every `/genpage` invocation.
+Follow these phases in order for every `/genpage` invocation, except for two requests that build nothing:
+
+- **Pull existing pages into the project** without editing them (for example "bring these pages into my repo",
+ "put the maker-made pages under source control"): follow [Pulling existing pages into the
+ project](#pulling-existing-pages-into-the-project) instead of the phases.
+- **Promote pages to another environment** (test, production, another development environment): read
+ [promotion.md](../../references/promotion.md) and follow it. Read it only for such a request. When the same
+ run also builds pages, read it after Phase 6.7.
**Every `<…>` you fill into a command goes in single quotes** (`'<working-dir>/prompt.txt'`, `'<App Name>'`).
PowerShell and bash expand nothing inside them — not `$name`, not `$(…)`, not a backtick — and a space does not split
@@ -1448,6 +1455,10 @@ referenced Custom APIs are a separate deployment prerequisite (bound by `name`),
A built-in operation binding (`WhoAmI`, `RetrieveVersion`) needs nothing at all: it names an
operation the platform defines, so there is no component to add or deploy.
+When the user asks to promote the pages to another environment, read
+[promotion.md](../../references/promotion.md) now: managed or unmanaged, full solution or patch, the version
+number, the dependency check, the import order, rollback, and what travels with a page.
+
### Phase 7: Verify in Browser (Optional)
After successful deployment, ask the user via `AskUserQuestion`:
@@ -1520,3 +1531,52 @@ deploy, verify, summarize. Built-in operations (`WhoAmI`, `RetrieveVersion`) are
Phase 3; Edit Phase 4 handles `dataverse_operation_discovery_required`, forwards this run's
built-in operation contract through every planner round, and re-probes `dataverse-operations`
before an add or replace is applied — the create flow's Phase 4.6b is not visited.
+
+---
+
+## Pulling existing pages into the project
+
+Use this when the user asks to bring existing generative pages — maker-authored ones included — into their project or
+source control without changing them. It runs no planner and no agent, uploads nothing and writes nothing to the
+environment: it only reads pages and writes their files locally.
+
+1. **Mode and environment.** Resolve the interaction mode (`resolve-interaction-mode.js`, as in Phase 1) and capture
+ the environment URL with `node "${PLUGIN_ROOT}/scripts/check-auth.js"` (add `--env '<envUrl>'` when the user named
+ the environment). Use that `envUrl` for every command below. Read its result as Phase 2a does: on `ok: false`
+ show the `message` verbatim and stop (`blocker: "usage"` alone means fix the command line and rerun it).
+2. **Choose the pages.** List them, never guess them:
+ - the pages of one app: `node "${PLUGIN_ROOT}/scripts/apps.js" list --env '<envUrl>'`, then
+ `node "${PLUGIN_ROOT}/scripts/genpage.js" list --env '<envUrl>' --app-id '<app-id>'`;
+ - every page in the environment, including pages in no app: `node "${PLUGIN_ROOT}/scripts/genpage.js" list --env '<envUrl>'`.
+
+ **Attended:** ask with `AskUserQuestion` (multi-select; label each page by `name`, the page id in the description).
+ **Unattended:** pull only the pages `$ARGUMENTS` names by id or exact name; when none is named, or a name matches
+ more than one page, halt and report what is needed.
+3. **Choose the folder.** The project root: the genpage project at or above the current directory (a folder holding a
+ `package.json` beside a `genpage.d.ts`), otherwise the current directory, or the folder the user names. Each page
+ lands in `<project-root>/<page-id>/` as `page.tsx`, `config.json` and, when the page has a prompt, `prompt.txt`.
+ When `<project-root>/<page-id>/` already exists, the download replaces the local files. **Attended:** ask
+ "Replace the local copy" or "Skip this page" for each such page. **Unattended:** skip it and report it. A pull
+ never replaces local work nobody agreed to replace.
+4. **Download** all the chosen pages in one command (add `--app-id '<app-id>'` only when every page came from that
+ app's list: with it, a page that is not in the app's saved navigation is refused):
+
+ ```powershell
+ node "${PLUGIN_ROOT}/scripts/genpage.js" download --env '<envUrl>' --page-id '<page-id1>,<page-id2>' --output-directory '<project-root>'
+ ```
+
+ It prints `{ "ok": true, "pages": [ { "pageId", "name", "directory", "files", "replaced", "removed" } ] }`
+ (Edit Phase 2 describes the fields). A failure (exit 1) leaves the folders as they were: report it and stop.
+5. **Record the base** of each page, so a later edit or upload can tell whether the deployed page changed since:
+
+ ```powershell
+ node "${PLUGIN_ROOT}/scripts/genpage-base.js" record --page-id '<page-id>' --file '<project-root>/<page-id>/page.tsx'
+ ```
+
+ Add `--app-id '<app-id>'` when the page came from an app's list. The marker holds hashes and ids only, so it may
+ be committed with the page.
+6. **Log and report.** Append a `## Pull` section to `workflow-log.md` in each pulled page's folder: the commands,
+ their JSON results, and every `AskUserQuestion` or `Unattended default:` line. Then show the user each page's name,
+ id and folder, and the pages skipped and why. Do not edit, build or upload the pulled pages in this request. To
+ change one later, run the edit flow and name the pulled `page.tsx` as the local copy (edit-flow.md, "Starting
+ from a local copy").
\ No newline at end of file
diff --git a/plugins/pcf/AGENTS.md b/plugins/pcf/AGENTS.md
index b3dfddd9d..a3f16ecac 100644
--- a/plugins/pcf/AGENTS.md
+++ b/plugins/pcf/AGENTS.md
@@ -32,7 +32,7 @@ Primary references: [`references/pcf-hosts.md`](references/pcf-hosts.md), [`refe
- **`scripts/pcf-build.js` → `scripts/lib/pcf-build.js`** — finds one `.pcfproj`, cleans by default, invokes the project-local `pcf-scripts` bin through `process.execPath`, checks `PcfBuildMode`, bundle size and unexplained outputs (`PCF_BUILD_*`, `PCF_BUNDLE_*`, `PCF_OUT_*`). `PcfBuildMode` only takes effect after the `Microsoft.Common.props` import.
- **`scripts/pcf-doctor.js` → `scripts/lib/pcf-doctor.js`** — checks local tools and project health for the requested needs. `--needs` accepts only `build,push`, and `--hosts` accepts only `model,pages`; unknown or empty selections fail before probing. Finding ids use `TOOL_*` and `PROJ_*`, plus matrix/host findings reused from manifest policy. The `.pcfproj` import scan is quote-aware, so a `Condition` containing a quoted `>` does not hide `Microsoft.Common.props` whether that attribute comes before or after `Project`.
- **`scripts/pcf-upgrade.js` → `scripts/lib/pcf-upgrade.js`** — plans and optionally applies bounded repairs: dependency alignment, build-mode placement and platform-library declaration alignment. Each replacement is written to a temp file in the same directory and renamed over the target, so a throw cannot truncate the project file. On any write failure every attempted target, including the one that threw, is restored from its in-memory original bytes; the result reports nothing applied and lists what was restored. A failed `npm install` rolls back the same way: `package-lock.json` returns to its pre-install bytes (or is removed if npm created it), every rewritten file returns to its original, nothing is reported applied, and the error says to run `npm ci` because `node_modules` may be partly updated. Step ids include `DEPS_TO_MATRIX`, `REINSTALL`, `BUILDMODE_PRODUCTION`, `PLATFORM_LIB_VERSION`, and manual migration ids for non-automatic changes. `REINSTALL` is selectable whenever the plan contains it. Each plan step has `requiresStep`; `DEPS_TO_MATRIX` requires `REINSTALL` because pinning `package.json` without reinstalling leaves a stale lockfile, and selecting `DEPS_TO_MATRIX` includes that step. `--steps` errors list every selectable id, including `REINSTALL`. An explicit `--steps` must normalize to at least one id; empty selections fail with usage before project discovery or apply, while omission keeps the unrestricted plan. It validates `--hosts`, refuses dirty trees unless `--allow-dirty` is explicit, and applies relative to the discovered PCF project root.
-- **`scripts/pcf-push.js`** — wraps `pac pcf push --environment` for developer verification. The skill must obtain consent before calling it because PAC publishes all pending customizations. It validates solution/publisher/control names before passing values to PAC, allows dev bundles only with bare `--allow-dev-bundle`, and verifies registration unless bare `--no-verify` is explicit.
+- **`scripts/pcf-push.js`** — wraps `pac pcf push --environment` for developer verification. The skill must obtain consent before calling it because PAC publishes all pending customizations. It validates solution/publisher/control names before passing values to PAC, allows dev bundles only with bare `--allow-dev-bundle`, and verifies registration unless bare `--no-verify` is explicit. When pac fails only because its publish-all step lost a SQL deadlock (the last `Sql Number:` after `Publishing All Customizations` is 1205), `scripts/lib/pcf-publish-retry.js` re-sends just that publish as `PublishAllXml`, at most twice (5 s, 15 s); any other answer (a 401 or a 429 included) or a lost answer is not re-sent, and the result adds `publishAttempts` (and `publishRetryError` when a re-send failed otherwise). Its HTTP client (`publishOnceClient`) passes the shared client's `sendOnce` predicate for `POST …/PublishAllXml`, so each attempt is exactly one send and `publishAttempts` counts the sends that reached the wire.
- **`scripts/verify-pcf.js` → `scripts/lib/pcf-dataverse.js` + `pcf-binding-verify.js`** — reads registration and FormXML metadata, then reports metadata evidence (`registered`, `bound(draft)`, `bound(published)`). `--intent` reads the canonical binding target from `bindings[].target` (`column` or `controlId`), with compatibility handling for older flat fields. An explicit intent `formType` restricts lookup to the documented `systemform.type`: `main` = 2, `quick-create` = 7, `quick-view` = 6, `card` = 11, `other` = 100; an omitted type preserves the default Main/Quick Create search and an unknown type is a usage error. The `/pcf` skill reports `runtime-not-checked` when no browser or manual runtime check was run. Binding findings use `PCF_BIND_*`; semantic clients are `phone`, `tablet`, `web`, mapped to FormXML factors only in `pcf-binding-verify.js`; explicit intent client arrays must normalize to at least one client.
- **`scripts/pcf-inventory.js` → `scripts/lib/pcf-dataverse.js`** — lists registered controls and optional where-used dependencies such as the bound `SystemForm` rows returned by Dataverse dependency APIs. It warns that dependency results are registered solution dependencies only and are not proof of Liquid or arbitrary text references.
- **`scripts/pcf-ci-build.js`** — generated-project CI helper. `--all` scaffolds templates and available recipes, runs installs and gates; `--templates` does the same for the templates only; `--latest` probes published dependency drift and keeps those resolved versions even when gates fail; `--package` builds a small package smoke through PAC solution packaging. Gate success requires exactly one JSON result whose records are manifest, code, lint, test and build, each `ok`. Package smoke parses every `<code path>` with the quote-aware XML reader, requires those files in the control folder, and compares them to bundle bytes snapshotted immediately after each build.
@@ -96,7 +96,7 @@ if (flagError) { process.stderr.write(`✗ ${flagError}\n${USAGE}\n`); process.e
`validateFlags` (`scripts/lib/dataverse-auth.js`) rejects unknown flags with a single-edit "did you mean" (via `scripts/lib/nearest-name.js`) and rejects a value-bearing flag passed bare or empty. It reads flag names from `argv` rather than the parsed object, because `--__proto__` goes through the inherited setter and never becomes an own property.
-Boolean switches are bare only. For example, use `--strict`, `--install`, `--no-clean`, `--allow-dev-bundle` and `--no-verify`; values such as `--strict=false` or `--no-verify=false` are usage errors, not false booleans.
+Boolean switches are bare only. For example, use `--strict`, `--install`, `--no-clean`, `--allow-dev-bundle` and `--no-verify`; values such as `--strict=false` or `--no-verify=false` are usage errors, not false booleans. Every CLI checks its switches with the one shared `scripts/lib/pcf-cli-flags.js` → `booleanFlagError(flags, names)`, which reports the first valued switch in `names` order; do not hand-write a per-CLI loop.
When a CLI test harness maps `parseArgs` to a fixed result, use `scripts/tests/helpers/fake-auth.js` → `validateFlagsFromParsed` so the harness exercises the real validator instead of a hand-written copy that can drift from it. `scripts/tests/helpers/cli-harness.js` → `loadCli(scriptPath, { requires, argv })` loads an entry point with injectable module stubs and a shadowed `process`, so a test can drive `main()` and assert the wire calls it makes rather than regex-matching source.
diff --git a/plugins/pcf/CHANGELOG.md b/plugins/pcf/CHANGELOG.md
index 79b79936d..fb4e675d3 100644
--- a/plugins/pcf/CHANGELOG.md
+++ b/plugins/pcf/CHANGELOG.md
@@ -16,9 +16,13 @@ First preview release: ships the `/pcf:pcf` skill, matrix-pinned templates and r
- Bundled SDK and HTTP client updated to model-apps 2.21.0 (SDK commit 0eef55f8c2d0). PCF still reads through them and publishes through PAC; removal of the SDK's unused PCF registration has no effect.
- The PCF guide explains why calls after an early-return guard or in an `else` branch are reported, and shows the positive guard block to use instead.
- An optional call with type arguments that is handed a context member, such as `factory?.<T>(context.device).captureImage()`, is now reported as a Pages call even when the factory returns its own object; call it without `?.` or keep the result in a local first.
+- `inventory`, `upgrade` and `ci-build` share one boolean-flag check; what each one refuses is unchanged.
+- The virtual templates' samples use Fluent v9 `Input` and `Button`.
### Fixed
+- When `pac pcf push` loses its publish to a SQL deadlock (1205), the publish is sent again, each re-send exactly once, and the result reports how many sends were made.
+- grid-customizer renders Choice cells with their formatted label.
- `check-auth.js` no longer reports success for an identity that cannot read customizations (no security role in the environment); it fails with `no_customization_role` and names a role to ask for.
- The push receipt (`pcf-receipt.json`) no longer carries an access token that a refused confirmation read quoted, and every file the SDK writes into a push's workspace goes through the same output guard as model-apps' scripts.
- A large result is no longer cut short on Linux and macOS: `emitResult`, the printer of an uncaught error, `check-auth.js`, the result printers of `pcf-inventory.js`, `verify-pcf.js` and `lint-pcf.js`, every script's usage error and the write-safety hook's message make their writes blocking before the process exits. What is printed and every exit status are unchanged; Windows was never affected.
diff --git a/plugins/pcf/docs/pcf-capabilities.md b/plugins/pcf/docs/pcf-capabilities.md
index 11fe4d5a2..0b2eecc91 100644
--- a/plugins/pcf/docs/pcf-capabilities.md
+++ b/plugins/pcf/docs/pcf-capabilities.md
@@ -44,7 +44,7 @@ This file records **shipped** behaviour only. Planned and unbuilt work is tracke
### Deploy — ✅ verified live
- `pcf-push.js` wraps `pac pcf push --environment` after the skill records consent.
-- The production bundle registered in Dataverse matched the local build hash, and the SQL 1205 publish-deadlock hint exists.
+- The production bundle registered in Dataverse matched the local build hash, and the SQL 1205 publish-deadlock hint exists. A publish-all step lost to a deadlock is re-sent at most twice (unit-tested; not yet observed live).
- Deploy publishes all customizations as part of the PAC operation.
### Binding verification — mixed evidence
diff --git a/plugins/pcf/recipes/grid-customizer/README.md b/plugins/pcf/recipes/grid-customizer/README.md
index 476af74b1..2a9c63946 100644
--- a/plugins/pcf/recipes/grid-customizer/README.md
+++ b/plugins/pcf/recipes/grid-customizer/README.md
@@ -31,7 +31,7 @@ A maker configures it after the control is packaged and imported:
1. Add the **Power Apps grid control** to the target table/grid.
2. Set the grid's **Customizer control** property to this component's full logical name, for example `<publisher prefix>_Contoso.Controls.GridCustomizer`.
3. Save and publish the table/grid customizations.
-4. Open the grid and verify the text-cell renderer/editor behavior.
+4. Open the grid and verify the text-cell renderer/editor and the Choice-cell renderer behavior.
Microsoft Learn states that multiple customizer controls can exist in an environment, but each grid can have only one customizer control assigned. Use a separate customizer component when two grids need incompatible renderer/editor behavior.
@@ -45,6 +45,7 @@ Designer paths:
- Registers a `PAOneGridCustomizer` in `init` through `EventName`.
- Keeps the documented `factory.fireEvent(eventName, customizer)` call isolated in `customizerBridge.ts`, which carries the `pcf-extension-pattern: grid-customizer` marker accepted by the code gate.
- Supplies `Text` cell renderer and editor overrides as a minimal, accessible starting point.
+- Supplies an `OptionSet` (Choice) cell renderer that shows the grid's `formattedValue` label, never the stored option number. It returns `null` when the value or the label is missing, so the grid's own renderer shows the cell.
- Returns `null` for `null` or `undefined` text values so the Power Apps grid uses its internal renderer fallback.
- Does not mutate grid row data, column definitions, or renderer/editor params.
- Keeps state per control instance; there is no module-global mutable state and no hard-coded element id.
@@ -52,7 +53,7 @@ Designer paths:
## Limits
- Model-driven apps only; Power Pages does not support virtual controls.
-- This recipe customizes text cells only. Add more data types in `customizers/CellRendererOverrides.tsx` and `customizers/CellEditorOverrides.tsx`.
+- This recipe customizes text cells (renderer and editor) and Choice cells (renderer only; the grid's own editor edits them). Add more data types in `customizers/CellRendererOverrides.tsx` and `customizers/CellEditorOverrides.tsx`.
- The customizer functions must stay pure and lightweight because the grid can call them repeatedly and can dispose rendered elements at any time.
- Renderers and editors must not write grid data directly. Use the editor callbacks supplied by the grid and normal platform save behavior.
- No network, file, navigation, or Dataverse Web API calls are used.
diff --git a/plugins/pcf/recipes/grid-customizer/__tests__/{{name}}.test.ts.tmpl b/plugins/pcf/recipes/grid-customizer/__tests__/{{name}}.test.ts.tmpl
index 3a049a5a3..63a50ce71 100644
--- a/plugins/pcf/recipes/grid-customizer/__tests__/{{name}}.test.ts.tmpl
+++ b/plugins/pcf/recipes/grid-customizer/__tests__/{{name}}.test.ts.tmpl
@@ -76,6 +76,43 @@ test("text renderer is pure and never mutates grid data", () => {
expect(props.value).toBe("Active");
});
+test("choice renderer shows the formatted label, not the stored option number", () => {
+ const renderer = cellRendererOverrides.OptionSet;
+ const container = document.createElement("div");
+
+ TestUtils.act(() => {
+ ReactDOM.render(renderer?.({ value: 100000001, formattedValue: "Preferred", isRTLMode: true }, { colDefs: [], columnIndex: 0 }) as React.ReactElement, container);
+ });
+
+ const cell = container.querySelector(".{{nameLower}}-choice-renderer") as HTMLElement;
+ expect(cell.textContent).toBe("Preferred");
+ expect(cell.getAttribute("title")).toBe("Preferred");
+ expect(cell.getAttribute("dir")).toBe("rtl");
+ expect(container.textContent).not.toContain("100000001");
+});
+
+test("choice renderer falls back to the grid renderer without a value or a label", () => {
+ const renderer = cellRendererOverrides.OptionSet;
+
+ expect(renderer?.({ value: null, formattedValue: "Preferred" }, { colDefs: [], columnIndex: 0 })).toBeNull();
+ expect(renderer?.({ value: undefined }, { colDefs: [], columnIndex: 0 })).toBeNull();
+ expect(renderer?.({ value: 100000001 }, { colDefs: [], columnIndex: 0 })).toBeNull();
+ expect(renderer?.({ value: 100000001, formattedValue: "" }, { colDefs: [], columnIndex: 0 })).toBeNull();
+});
+
+test("choice renderer is pure and never mutates grid data", () => {
+ const renderer = cellRendererOverrides.OptionSet;
+ const rowData = Object.freeze({ __rec_id: "row-6" });
+ const props = Object.freeze({ value: 1, formattedValue: "Active" });
+ const params = Object.freeze({ colDefs: Object.freeze([]), columnIndex: 0, rowData });
+
+ const first = renderer?.(props, params) as React.ReactElement;
+ const second = renderer?.(props, params) as React.ReactElement;
+
+ expect(first.props).toEqual(second.props);
+ expect(rowData).toEqual({ __rec_id: "row-6" });
+ expect(props.value).toBe(1);
+});
test("text editor calls the grid change callback without mutating params", () => {
const editor = cellEditorOverrides.Text;
const rowData = Object.freeze({ __rec_id: "row-2" });
diff --git a/plugins/pcf/recipes/grid-customizer/{{name}}/css/{{name}}.css.tmpl b/plugins/pcf/recipes/grid-customizer/{{name}}/css/{{name}}.css.tmpl
index 8c2fe4862..5bbe48fca 100644
--- a/plugins/pcf/recipes/grid-customizer/{{name}}/css/{{name}}.css.tmpl
+++ b/plugins/pcf/recipes/grid-customizer/{{name}}/css/{{name}}.css.tmpl
@@ -2,7 +2,8 @@
display: contents;
}
-.{{nameLower}}-text-renderer {
+.{{nameLower}}-text-renderer,
+.{{nameLower}}-choice-renderer {
box-sizing: border-box;
display: block;
min-width: 0;
diff --git a/plugins/pcf/recipes/grid-customizer/{{name}}/customizers/CellRendererOverrides.tsx.tmpl b/plugins/pcf/recipes/grid-customizer/{{name}}/customizers/CellRendererOverrides.tsx.tmpl
index b73e3a930..c874714d1 100644
--- a/plugins/pcf/recipes/grid-customizer/{{name}}/customizers/CellRendererOverrides.tsx.tmpl
+++ b/plugins/pcf/recipes/grid-customizer/{{name}}/customizers/CellRendererOverrides.tsx.tmpl
@@ -16,4 +16,21 @@ export const cellRendererOverrides: CellRendererOverrides = {
text,
);
},
-};
+ // Choice (option set) cells: `value` is the stored option number and `formattedValue` is the
+ // label the grid already resolved in the user's language, so show the label, never the number.
+ // Without a label, return null so the grid's internal renderer shows the choice instead.
+ OptionSet: (props) => {
+ if (props.value == null || !props.formattedValue) return null;
+ const label = props.formattedValue;
+
+ return React.createElement(
+ "span",
+ {
+ className: "{{nameLower}}-choice-renderer",
+ dir: props.isRTLMode ? "rtl" : undefined,
+ title: label,
+ },
+ label,
+ );
+ },
+};
\ No newline at end of file
diff --git a/plugins/pcf/recipes/hierarchy-tree/README.md b/plugins/pcf/recipes/hierarchy-tree/README.md
index e387d11de..1b4b8744a 100644
--- a/plugins/pcf/recipes/hierarchy-tree/README.md
+++ b/plugins/pcf/recipes/hierarchy-tree/README.md
@@ -43,7 +43,7 @@ PCF datasets expose the records on the current loaded page through `sortedRecord
## Accessibility and localization
-The tree uses `role="tree"`, `role="treeitem"`, `aria-expanded`, and `aria-level`. Arrow Left collapses a node, Arrow Right expands it, and Enter opens the record. User-visible strings are in the recipe's `.resx` resource file.
+The tree uses `role="tree"`, `role="treeitem"`, `aria-expanded`, and `aria-level`. Arrow Left collapses a node, Arrow Right expands it, and Enter opens the record. The tree has one roving tab stop: only the focused tree item is in the tab order, the expand and **Open** buttons inside tree items are not, and focus stays on the same item when `updateView` re-renders the tree. The recipe tests pin both. User-visible strings are in the recipe's `.resx` resource file.
## Learn references confirmed
diff --git a/plugins/pcf/recipes/hierarchy-tree/__tests__/{{name}}.test.ts.tmpl b/plugins/pcf/recipes/hierarchy-tree/__tests__/{{name}}.test.ts.tmpl
index 3febaf9ce..30501fd07 100644
--- a/plugins/pcf/recipes/hierarchy-tree/__tests__/{{name}}.test.ts.tmpl
+++ b/plugins/pcf/recipes/hierarchy-tree/__tests__/{{name}}.test.ts.tmpl
@@ -285,3 +285,37 @@ test("nested tree item keyboard handling does not bubble to ancestors", () => {
visibleTreeItems()[1].dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
expect(document.activeElement?.textContent).toBe("GrandchildOpen");
});
+
+test("focus stays on a non-first tree item across updateView", () => {
+ const { container, control, context } = mount(deepHierarchyDataSet());
+ const visibleTreeItems = () => Array.from(container.querySelectorAll('[role="treeitem"]')) as HTMLElement[];
+
+ visibleTreeItems()[0].focus();
+ visibleTreeItems()[0].dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
+ expect(document.activeElement?.textContent).toBe("ChildOpenGrandchildOpen");
+
+ control.updateView(context);
+
+ // The re-render replaces the tree's elements, so the focused element must be the new "Child" node,
+ // and it must keep the single roving tab stop rather than handing it back to the first item.
+ expect(container.contains(document.activeElement)).toBe(true);
+ expect((document.activeElement as HTMLElement).getAttribute("aria-level")).toBe("2");
+ expect(document.activeElement?.textContent).toBe("ChildOpenGrandchildOpen");
+ expect(visibleTreeItems().map((item) => item.tabIndex)).toEqual([-1, 0, -1]);
+});
+
+test("buttons nested in tree items stay out of the tab order", () => {
+ const { container, control, context } = mount(deepHierarchyDataSet());
+ const treeButtons = () => Array.from(container.querySelectorAll('[role="tree"] button')) as HTMLButtonElement[];
+
+ expect(treeButtons().length).toBeGreaterThan(0);
+ expect(treeButtons().map((button) => button.tabIndex)).toEqual(treeButtons().map(() => -1));
+
+ const visibleTreeItems = () => Array.from(container.querySelectorAll('[role="treeitem"]')) as HTMLElement[];
+ visibleTreeItems()[0].focus();
+ visibleTreeItems()[0].dispatchEvent(new KeyboardEvent("keydown", { key: "End", bubbles: true }));
+ control.updateView(context);
+
+ expect(treeButtons().map((button) => button.tabIndex)).toEqual(treeButtons().map(() => -1));
+ expect(Array.from(container.querySelectorAll('[role="tree"] [tabindex="0"]')).map((item) => item.getAttribute("role"))).toEqual(["treeitem"]);
+});
\ No newline at end of file
diff --git a/plugins/pcf/references/pcf-deploy.md b/plugins/pcf/references/pcf-deploy.md
index 22ef5ad46..5795d5456 100644
--- a/plugins/pcf/references/pcf-deploy.md
+++ b/plugins/pcf/references/pcf-deploy.md
@@ -17,6 +17,8 @@ node "${PLUGIN_ROOT}/scripts/pcf-push.js" --project <dir> --env <url> (--solutio
`pcf-push.js` wraps `pac pcf push --environment`; the skill obtains consent because `pac pcf push` publishes all pending customizations in the environment.
+When the push fails only because its final publish-all step was chosen as a SQL deadlock victim (SQL 1205), the import has already succeeded, so `pcf-push.js` sends that publish again (Web API `PublishAllXml`) at most twice, 5 and 15 seconds apart. It never re-runs `pac`, never re-sends after another error (a 401 or a 429 included) or a lost answer, sends each attempt exactly once, and reports `publishAttempts` (pac's attempt plus the publishes it actually sent) whenever it tried. See [pcf-troubleshooting.md](pcf-troubleshooting.md).
+
Boolean switches are bare. Use `--allow-dev-bundle` only when intentionally deploying a development bundle, and `--no-verify` only when intentionally skipping registration read-back; valued forms such as `--allow-dev-bundle=false` and `--no-verify=false` fail as usage errors.
## Versions and cache busting
diff --git a/plugins/pcf/references/pcf-recipes.md b/plugins/pcf/references/pcf-recipes.md
index 54090ce83..4e31ba021 100644
--- a/plugins/pcf/references/pcf-recipes.md
+++ b/plugins/pcf/references/pcf-recipes.md
@@ -38,7 +38,7 @@ The catalog is rendered from recipe metadata. Recipes are starting points, not c
- Template: `field-virtual`.
- Hosts: model-driven apps; Power Pages not certified in this release.
- Key property: `EventName`.
-- Limits: one customizer per grid, model-driven only, pure renderers/editors. The editor preserves the typed-start character from the official grid customizer `charPress` callback.
+- Limits: one customizer per grid, model-driven only, pure renderers/editors. The editor preserves the typed-start character from the official grid customizer `charPress` callback. A Choice renderer example, for `OptionSet` columns, shows the grid's formatted label.
## Hierarchy Tree
diff --git a/plugins/pcf/references/pcf-troubleshooting.md b/plugins/pcf/references/pcf-troubleshooting.md
index 6a815d707..70580efb8 100644
--- a/plugins/pcf/references/pcf-troubleshooting.md
+++ b/plugins/pcf/references/pcf-troubleshooting.md
@@ -182,13 +182,13 @@ If project lint reports that no `ControlManifest.Input.xml` files were found, pa
### Push fails while publishing all customizations with SQL 1205
-**Symptom**: `pac pcf push` imports the temporary solution, then fails at `Publishing All Customizations...` with `Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205`. `pcf-push.js` returns `ok: false` with a deadlock hint.
+**Symptom**: `pac pcf push` imports the temporary solution, then fails at `Publishing All Customizations...` with `Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205`. `pcf-push.js` has already sent that publish again (Web API `PublishAllXml`) at most twice, 5 and 15 seconds apart, and every attempt lost a deadlock; it returns `ok: false` with a deadlock hint and `publishAttempts: 3`. A re-sent publish answered with another error, or whose answer never arrived, is not sent again: the result carries `publishRetryError` and the attempts made.
**Candidate causes**: SQL Server error 1205 means the server chose this transaction as a deadlock victim ([MSSQLSERVER_1205](https://learn.microsoft.com/en-us/sql/relational-databases/errors-events/mssqlserver-1205-database-engine-error)). On a shared environment this happens when another import or publish is running at the same time. Observed on 2026-09-29 on a shared test environment during a concurrent publish. It is not caused by the project.
**Discriminating checks**: The pac output shows `Importing the temporary solution wrapper into the current org: done.` before the error, so the build and import succeeded. `pcf-inventory.js --env <url> --control <prefix>_<namespace>.<constructor>` shows whether the control is already registered. HTTP 429 responses from the same environment around the same time point to the same contention.
-**Fix**: Wait a minute, then re-run the same `pcf-push.js` command. If the environment stays busy, publish from Maker (**Publish all customizations**) once it is quiet, or push to a less contended development environment. Do not change the project to work around it.
+**Fix**: Wait a minute, then re-run the same `pcf-push.js` command. A push whose re-sent publish succeeded returns `ok: true` with `publishAttempts` and needs nothing more. If the environment stays busy, publish from Maker (**Publish all customizations**) once it is quiet, or push to a less contended development environment. Do not change the project to work around it.
**Verify**: The re-run push returns `ok: true` with a registration read-back whose version matches the manifest.
diff --git a/plugins/pcf/scripts/lib/pcf-cli-flags.js b/plugins/pcf/scripts/lib/pcf-cli-flags.js
index 8bc299bc6..edc7b12d7 100644
--- a/plugins/pcf/scripts/lib/pcf-cli-flags.js
+++ b/plugins/pcf/scripts/lib/pcf-cli-flags.js
@@ -1,5 +1,9 @@
'use strict';
+// The one boolean-switch check every pcf CLI shares. parseArgs reads `--flag=value` and `--flag value`
+// on any flag, so a switch given a value would otherwise read as true (`--apply=false` would apply).
+// Switches are bare only: any string value, including an empty one, is a usage error. `names` is
+// checked in its declared order, so the first refused switch in that list is the one reported.
function booleanFlagError(flags, names) {
for (const name of names) {
const value = flags[name];
diff --git a/plugins/pcf/scripts/lib/pcf-publish-retry.js b/plugins/pcf/scripts/lib/pcf-publish-retry.js
new file mode 100644
index 000000000..c6a705f76
--- /dev/null
+++ b/plugins/pcf/scripts/lib/pcf-publish-retry.js
@@ -0,0 +1,115 @@
+'use strict';
+// A bounded re-send of the ONE request `pac pcf push` lost to a SQL deadlock: its final publish of all customizations.
+//
+// `pac pcf push` builds, imports a temporary solution and then publishes all customizations, in one process. On a shared environment the
+// publish can be chosen as a SQL Server deadlock victim (error 1205) when another import or publish runs at the same time. pac prints
+// (observed on a live push, on stdout, after the import had succeeded):
+// Importing the temporary solution wrapper into the current org: done.
+// Publishing All Customizations...
+// Error: Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205
+// A deadlock victim's transaction is rolled back, so that publish did nothing and sending it again is safe. Re-running the whole push would
+// rebuild and re-import as well, so only the publish is sent again here, as the documented unbound PublishAllXml action — the same
+// request pac makes for that step:
+// POST <envUrl>/api/data/v9.2/PublishAllXml {}
+// See: https://learn.microsoft.com/sql/relational-databases/errors-events/mssqlserver-1205-database-engine-error
+// https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/publishallxml
+//
+// Nothing else is re-sent: a failure before the publish step, any other error, and an answer that never arrived (the transport failed or
+// timed out, so the publish may still be running) all stop at once. This loop must be the ONLY layer that re-sends the publish, so the
+// client it uses is made by `publishOnceClient`: the shared HTTP client's own `publishOnce` rule still re-sends a publish refused with a
+// 401 (after a token refresh) or with a service-protection 429, which here would multiply the attempts (up to six extra sends behind one
+// reported re-send). The client's documented `sendOnce` seam closes every re-send for `POST …/PublishAllXml` without changing the
+// shared client (sdk-http-client.js is a byte copy kept in sync with model-apps) for any other request.
+const { SQL_DEADLOCK_VICTIM, isSqlDeadlockVictim, createAzHttpClient } = require('./sdk-http-client.js');
+const { makeRequest } = require('./dataverse-auth.js');
+
+// pac's progress line for its publish step. Only a deadlock reported AFTER it is the publish's own; a 1205 during the import is not retried.
+const PUBLISH_STEP_MARKER = 'Publishing All Customizations';
+// At most two re-sends after pac's own attempt, waiting longer each time so the competing import or publish can finish.
+const PUBLISH_RETRY_DELAYS_MS = Object.freeze([5000, 15000]);
+
+const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/** True for the publish this module re-sends: `POST <envUrl>/api/data/v9.x/PublishAllXml` (the SDK always passes a full URL). */
+function isPublishAllRequest(method, url) {
+ if (String(method).toUpperCase() !== 'POST') return false;
+ try {
+ return /\/PublishAllXml$/i.test(new URL(String(url)).pathname);
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * An HTTP client for the publish re-send that sends each PublishAllXml exactly once, whatever answers it, and counts the publishes that
+ * actually reached the transport, so the attempt count reported is the number of sends, not of loop turns (a token failure sends none).
+ * `deps` is the HTTP client's test seam (getToken, request, sleep); every other request keeps the shared client's behaviour.
+ * Answers `{ httpClient, sends }`, where `sends()` is the PublishAllXml send count so far.
+ */
+function publishOnceClient(envOrigin, deps = {}) {
+ const request = deps.request || makeRequest;
+ let sends = 0;
+ const httpClient = createAzHttpClient(envOrigin, {
+ ...deps,
+ sendOnce: isPublishAllRequest,
+ request: (options) => {
+ if (isPublishAllRequest(options && options.method, options && options.url)) sends += 1;
+ return request(options);
+ },
+ });
+ return { httpClient, sends: () => sends };
+}
+
+/**
+ * True when a failed `pac pcf push` result shows its publish-all step lost a SQL deadlock: pac's publish line is present and the last
+ * SQL number after it is 1205 (SQL_DEADLOCK_VICTIM reads the LAST `Sql Number:` so a quoted 1205 inside another SQL error does not count).
+ * A spawn error, a timeout or a success is never one.
+ */
+function isPublishStepDeadlock(result) {
+ if (!result || result.error || (result.status || 0) === 0) return false;
+ const text = [result.stdout, result.stderr].filter(Boolean).join('\n');
+ const at = text.lastIndexOf(PUBLISH_STEP_MARKER);
+ return at !== -1 && SQL_DEADLOCK_VICTIM.test(text.slice(at));
+}
+
+/**
+ * Send PublishAllXml again, at most `delays.length` times, while each answer is a SQL deadlock victim.
+ * `dataverse` is the SDK's Dataverse client, whose `post` answers `{ status, headers, body }` and throws only when the transport fails.
+ * Answers `{ published, retries, outcome, reason? }`: outcome is `published`, `deadlock` (every re-send lost a deadlock too), `error`
+ * (another answer, not re-sent) or `indeterminate` (no answer arrived, not re-sent). `retries` is the number of re-sends: `sends()`
+ * (publishOnceClient's wire count) when given, otherwise the number of `post` calls.
+ */
+async function retryPublishAll(dataverse, { sleep = wait, delays = PUBLISH_RETRY_DELAYS_MS, sends = null } = {}) {
+ let calls = 0;
+ const done = (result) => ({ ...result, retries: typeof sends === 'function' ? sends() : calls });
+ for (const delay of delays) {
+ await sleep(delay);
+ calls += 1;
+ let answer;
+ try {
+ answer = await dataverse.post('/PublishAllXml', {});
+ } catch (err) {
+ return done({ published: false, outcome: 'indeterminate', reason: errorText(err) });
+ }
+ if (!answer) return done({ published: false, outcome: 'indeterminate', reason: 'PublishAllXml returned no answer' });
+ if (answer.status >= 200 && answer.status < 300) return done({ published: true, outcome: 'published' });
+ if (!isSqlDeadlockVictim({ statusCode: answer.status, body: answer.body })) {
+ return done({ published: false, outcome: 'error', reason: answerText(answer) });
+ }
+ }
+ return done({ published: false, outcome: 'deadlock' });
+}
+
+function errorText(err) {
+ return (err && err.message ? String(err.message) : String(err)).slice(0, 300);
+}
+
+// Dataverse errors arrive as { error: { code, message } }; some surfaces capitalize the envelope as { Error: { message } }.
+function answerText(answer) {
+ const body = answer.body;
+ const envelope = body && (body.error || body.Error);
+ const message = envelope && envelope.message ? envelope.message : (typeof body === 'string' ? body : '');
+ return `HTTP ${answer.status}${message ? `: ${String(message).trim().slice(0, 300)}` : ''}`;
+}
+
+module.exports = { PUBLISH_STEP_MARKER, PUBLISH_RETRY_DELAYS_MS, isPublishStepDeadlock, isPublishAllRequest, publishOnceClient, retryPublishAll };
diff --git a/plugins/pcf/scripts/pcf-ci-build.js b/plugins/pcf/scripts/pcf-ci-build.js
index 8d8deec7f..24a810d63 100644
--- a/plugins/pcf/scripts/pcf-ci-build.js
+++ b/plugins/pcf/scripts/pcf-ci-build.js
@@ -7,6 +7,7 @@ const path = require('node:path');
const crypto = require('node:crypto');
const zlib = require('node:zlib');
const { parseArgs, validateFlags, emitResult } = require('./lib/dataverse-auth.js');
+const { booleanFlagError } = require('./lib/pcf-cli-flags.js');
const { spawnResultSync } = require('./lib/process-runner.js');
const { listTemplates, listRecipes, planScaffold, writeScaffold } = require('./lib/pcf-scaffold.js');
const { loadMatrix, dependencySet } = require('./lib/pcf-matrix.js');
@@ -642,9 +643,8 @@ function main(argv = process.argv.slice(2)) {
const flags = parsed.flags;
// parseArgs accepts `--flag=value` on any flag, so a boolean flag given a value would otherwise
// read as true (`--templates=field-standard` would silently build every template).
- for (const booleanFlag of BOOLEAN_FLAGS) {
- if (flags[booleanFlag] !== undefined && flags[booleanFlag] !== true) usageError(`--${booleanFlag} does not take a value`);
- }
+ const booleanError = booleanFlagError(flags, BOOLEAN_FLAGS);
+ if (booleanError) usageError(booleanError);
const selectors = [Boolean(flags.all), Boolean(flags.templates), Boolean(flags.template), Boolean(flags.recipe), Boolean(flags.package)].filter(Boolean).length;
if (selectors !== 1) usageError('Choose exactly one of --all, --templates, --template <id>, --recipe <id>, or --package.');
const result = runCiBuild({
diff --git a/plugins/pcf/scripts/pcf-inventory.js b/plugins/pcf/scripts/pcf-inventory.js
index 274672bd4..a0896cb77 100644
--- a/plugins/pcf/scripts/pcf-inventory.js
+++ b/plugins/pcf/scripts/pcf-inventory.js
@@ -3,6 +3,7 @@
const path = require('node:path');
const { parseArgs, validateFlags } = require('./lib/dataverse-auth.js');
+const { booleanFlagError } = require('./lib/pcf-cli-flags.js');
const { makeWritesBlocking } = require('./lib/output-redaction.js');
const {
WHERE_USED_CAVEAT,
@@ -41,8 +42,10 @@ async function main(argv = process.argv.slice(2)) {
const env = String(flags.env);
const workspace = flags.workspace ? String(flags.workspace) : path.resolve('.maker-workspace', 'pcf-inventory');
- const includeManaged = readBooleanFlag(flags, 'include-managed');
- const withWhereUsed = readBooleanFlag(flags, 'where-used');
+ const booleanError = booleanFlagError(flags, ['include-managed', 'where-used']);
+ if (booleanError) usageError(booleanError);
+ const includeManaged = Boolean(flags['include-managed']);
+ const withWhereUsed = Boolean(flags['where-used']);
const output = { ok: true, controls: [] };
if (withWhereUsed) output.whereUsedCaveat = WHERE_USED_CAVEAT;
@@ -107,14 +110,6 @@ function isDefaultInventoryControl(control) {
return control && !control.isManaged && !name.startsWith('MscrmControls.') && !name.startsWith('Microsoft.');
}
-function readBooleanFlag(flags, name) {
- const value = flags[name];
- if (value === undefined) return false;
- if (value === true) return true;
- usageError(`--${name} does not take a value`);
- return false;
-}
-
function missingControlMessage(controlName) {
const expected = controlName.includes('_') ? '<publisherPrefix>_<namespace>.<constructor>' : `<publisherPrefix>_${controlName}`;
return `No PCF custom control named '${controlName}' was found. Registered controls use the prefixed form '${expected}' (for example, <publisherPrefix>_<namespace>.<constructor>), not just the manifest namespace and constructor.`;
diff --git a/plugins/pcf/scripts/pcf-push.js b/plugins/pcf/scripts/pcf-push.js
index 281aaf4a3..8538adc7d 100644
--- a/plugins/pcf/scripts/pcf-push.js
+++ b/plugins/pcf/scripts/pcf-push.js
@@ -13,6 +13,7 @@ const { pcfprojBuildMode } = require('./lib/pcf-doctor.js');
const { makePcfSdk, findCustomControl, solutionPrefix } = require('./lib/pcf-dataverse.js');
const { parseManifest } = require('./lib/pcf-manifest.js');
const { booleanFlagError } = require('./lib/pcf-cli-flags.js');
+const { isPublishStepDeadlock, publishOnceClient, retryPublishAll } = require('./lib/pcf-publish-retry.js');
const { emitSkillCompleted } = require('./lib/telemetry/skill-completed.js');
const USAGE = `Usage:
@@ -157,13 +158,21 @@ async function main(argv = process.argv.slice(2)) {
}, { stage: 'push', timedOut: true });
}
- if ((push.status || 0) !== 0) {
+ // A push that failed only because its final publish lost a SQL deadlock has already built and imported the control, so only that
+ // publish is sent again (lib/pcf-publish-retry.js). Every other failure, and a publish that still fails, is reported as before, with
+ // the number of publish attempts added when a re-send was tried.
+ let publishRetry = null;
+ if (isPublishStepDeadlock(push)) publishRetry = await resendDeadlockedPublish(envOrigin, projectDir);
+
+ if ((push.status || 0) !== 0 && !(publishRetry && publishRetry.published)) {
return finish(false, {
ok: false,
stage: 'push',
status: push.status,
...(push.error ? { error: scrubSecrets(errorReason(push.error)) } : {}),
hints: pushHints(push),
+ ...(publishRetry ? { publishAttempts: 1 + publishRetry.retries } : {}),
+ ...(publishRetry && publishRetry.reason ? { publishRetryError: scrubSecrets(publishRetry.reason) } : {}),
logTail: readBuildLogTail(projectDir),
stdout: scrubbedTail(push.stdout, 60),
stderr: scrubbedTail(push.stderr, 60),
@@ -208,9 +217,26 @@ async function main(argv = process.argv.slice(2)) {
version: expectedVersion,
registered: stripPrivateRegistration(registered),
receipt,
+ ...(publishRetry ? { publishAttempts: 1 + publishRetry.retries } : {}),
}, { stage: 'done', ok, registered: !!registered.ok });
}
+// Re-sends the publish pac lost to a deadlock through the same SDK workspace the registration read-back uses. A client that cannot be
+// made (no token, for example) sent nothing, so it reports the reason with no re-send rather than throwing out of the push.
+// The client sends each PublishAllXml exactly once and counts the sends (publishOnceClient), so `retries` — and the publishAttempts
+// reported from it — is the number of publishes that reached the wire, never more re-sends hidden behind one loop turn.
+async function resendDeadlockedPublish(envOrigin, projectDir) {
+ let sdk;
+ let wire;
+ try {
+ wire = publishOnceClient(envOrigin);
+ sdk = await makePcfSdk(envOrigin, path.join(projectDir, '.maker-workspace', 'pcf-push'), wire.httpClient);
+ } catch (err) {
+ return { published: false, retries: 0, outcome: 'error', reason: errorReason(err) };
+ }
+ return retryPublishAll(sdk.dataverse, { sends: wire.sends });
+}
+
// What a push's result says, in the closed vocabulary of lib/telemetry/skill-completed.js — never a control, solution or environment name.
// done, ok → success; registration verified | skipped (--no-verify)
// done, registration not read back → verify-failed push timed out → timeout
diff --git a/plugins/pcf/scripts/pcf-upgrade.js b/plugins/pcf/scripts/pcf-upgrade.js
index 4d491d368..007e9fd00 100644
--- a/plugins/pcf/scripts/pcf-upgrade.js
+++ b/plugins/pcf/scripts/pcf-upgrade.js
@@ -3,6 +3,7 @@
const path = require('node:path');
const { parseArgs, validateFlags, emitResult } = require('./lib/dataverse-auth.js');
+const { booleanFlagError } = require('./lib/pcf-cli-flags.js');
const { runUpgrade } = require('./lib/pcf-upgrade.js');
const { makeWritesBlocking } = require('./lib/output-redaction.js');
@@ -46,9 +47,8 @@ function runMain(argv = process.argv.slice(2)) {
if (flagError) usageError(flagError);
const flags = parsed.flags;
- for (const booleanFlag of ['apply', 'allow-dirty', 'no-install']) {
- if (flags[booleanFlag] !== undefined && flags[booleanFlag] !== true) usageError(`--${booleanFlag} does not take a value`);
- }
+ const booleanError = booleanFlagError(flags, ['apply', 'allow-dirty', 'no-install']);
+ if (booleanError) usageError(booleanError);
const hosts = splitList(flags.hosts, ['model']);
validateHosts(hosts, flags.hosts !== undefined);
const steps = splitList(flags.steps, []);
diff --git a/plugins/pcf/scripts/tests/pcf-build.test.js b/plugins/pcf/scripts/tests/pcf-build.test.js
index 569c16cff..05d6fc0bf 100644
--- a/plugins/pcf/scripts/tests/pcf-build.test.js
+++ b/plugins/pcf/scripts/tests/pcf-build.test.js
@@ -89,7 +89,7 @@ test('buildControl runs pcf-scripts build through node with shell-free productio
assert.equal(result.controls.length, 1);
assert.equal(result.controls[0].bundleBytes, 128);
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -110,7 +110,7 @@ test('buildControl fails a clean exit that produced no processed control', () =>
assert.match(result.error, /no processed control/i);
assert.match(result.error, /ControlManifest\.xml/);
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -139,7 +139,7 @@ test('buildControl cleans old output and classifies unexplained files without re
assert.ok(bundleFindings(result, { bundle: { webpackDefaultMaxBytes: 5 * 1024 * 1024, warnAtFraction: 0.8 } })
.some((finding) => finding.code === 'PCF_OUT_UNEXPLAINED_FILE' && /debug\.map/.test(finding.message) && /remove|declare|exclude/i.test(finding.fix)));
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -174,9 +174,9 @@ test('buildControl refuses absolute, parent, and project-root outDir values with
assert.match(result.error, new RegExp(escapeRegExp(String(outDir))));
assert.equal(fs.readFileSync(sentinel, 'utf8'), item);
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
- fs.rmSync(absoluteOut, { recursive: true, force: true });
- fs.rmSync(parentSibling, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
+ fs.rmSync(absoluteOut, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
+ fs.rmSync(parentSibling, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
}
});
@@ -208,8 +208,8 @@ test('buildControl refuses an outDir symlink or junction that resolves outside t
assert.match(result.error, /inside the PCF project/i);
assert.equal(fs.readFileSync(sentinel, 'utf8'), 'outside');
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
- fs.rmSync(outside, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
+ fs.rmSync(outside, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -343,7 +343,7 @@ test('findControlProject walks up from a nested folder to the nearest pcfproj ro
assert.equal(found.manifests.length, 1);
assert.equal(found.packageJson, path.join(dir, 'package.json'));
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
diff --git a/plugins/pcf/scripts/tests/pcf-check-version.test.js b/plugins/pcf/scripts/tests/pcf-check-version.test.js
index 378d007bd..5c8bdcb7d 100644
--- a/plugins/pcf/scripts/tests/pcf-check-version.test.js
+++ b/plugins/pcf/scripts/tests/pcf-check-version.test.js
@@ -17,6 +17,6 @@ test('readMarketplaceName does not read checkout-root marketplace metadata for p
assert.match(formatUpdateMessage('pcf', '1.0.0', '1.0.1', readMarketplaceName(root), 'copilot'), /copilot plugin update pcf/);
assert.doesNotMatch(formatUpdateMessage('pcf', '1.0.0', '1.0.1', readMarketplaceName(root), 'copilot'), /marketplace update/);
} finally {
- fs.rmSync(root, { recursive: true, force: true });
+ fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
diff --git a/plugins/pcf/scripts/tests/pcf-ci-build.test.js b/plugins/pcf/scripts/tests/pcf-ci-build.test.js
index 816688002..ee4093bbe 100644
--- a/plugins/pcf/scripts/tests/pcf-ci-build.test.js
+++ b/plugins/pcf/scripts/tests/pcf-ci-build.test.js
@@ -19,7 +19,7 @@ function tmpRoot() {
return root;
}
test.after(() => {
- for (const root of createdRoots) fs.rmSync(root, { recursive: true, force: true });
+ for (const root of createdRoots) fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
});
function deps(overrides = {}) {
diff --git a/plugins/pcf/scripts/tests/pcf-cli-flags.test.js b/plugins/pcf/scripts/tests/pcf-cli-flags.test.js
new file mode 100644
index 000000000..139ff2be7
--- /dev/null
+++ b/plugins/pcf/scripts/tests/pcf-cli-flags.test.js
@@ -0,0 +1,102 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const { booleanFlagError } = require('../lib/pcf-cli-flags.js');
+const { parseArgs } = require('../lib/dataverse-auth.js');
+
+const scriptsDir = path.join(__dirname, '..');
+
+// Every case below fails with a usage error before any project, SDK or network work starts, so
+// spawning the real entry point is cheap and pins the whole contract a caller sees: exit code,
+// empty stdout and the stderr message.
+function runCli(script, argv) {
+ return spawnSync(process.execPath, [path.join(scriptsDir, script), ...argv], {
+ encoding: 'utf8',
+ env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_PCF_OPTOUT: '1' },
+ });
+}
+
+// `--name=value`, `--name=` and `--name <value>` all reach the parsed flags as a string, and each
+// must stay a usage error rather than reading as true or false.
+function refusedForms(name) {
+ return [[`--${name}=false`], [`--${name}=true`], [`--${name}=`], [`--${name}`, 'yes']];
+}
+
+const COMMANDS = [
+ {
+ script: 'pcf-inventory.js',
+ prefix: ['--env', 'https://contoso.crm.dynamics.com'],
+ booleans: ['include-managed', 'where-used'],
+ },
+ {
+ script: 'pcf-upgrade.js',
+ prefix: ['--project', path.join(scriptsDir, 'does-not-exist')],
+ booleans: ['apply', 'allow-dirty', 'no-install'],
+ },
+ {
+ script: 'pcf-ci-build.js',
+ prefix: [],
+ booleans: ['all', 'templates', 'latest', 'keep', 'package'],
+ },
+];
+
+for (const { script, prefix, booleans } of COMMANDS) {
+ test(`${script} refuses a value on each boolean flag with a usage error`, () => {
+ for (const name of booleans) {
+ for (const form of refusedForms(name)) {
+ const result = runCli(script, [...prefix, ...form]);
+ const label = `${script} ${form.join(' ')}`;
+ assert.equal(result.status, 1, label);
+ assert.equal(result.stdout, '', label);
+ assert.match(result.stderr, /Usage:/, label);
+ assert.match(result.stderr, new RegExp(`--${name} does not take a value`), label);
+ }
+ }
+ });
+
+ test(`${script} reports the first refused boolean flag in its declared order, not argv order`, () => {
+ const reversed = [...booleans].reverse().map((name) => `--${name}=1`);
+ const result = runCli(script, [...prefix, ...reversed]);
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, new RegExp(`--${booleans[0]} does not take a value`));
+ for (const name of booleans.slice(1)) assert.doesNotMatch(result.stderr, new RegExp(`--${name} does not take a value`));
+ });
+}
+
+test('pcf-inventory checks --env before boolean flag values', () => {
+ const result = runCli('pcf-inventory.js', ['--where-used=false']);
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /--env is required/);
+ assert.doesNotMatch(result.stderr, /does not take a value/);
+});
+
+test('pcf-upgrade accepts bare boolean flags and checks them before --hosts', () => {
+ const bare = runCli('pcf-upgrade.js', ['--apply', '--allow-dirty', '--no-install', '--hosts', 'console']);
+ assert.equal(bare.status, 1);
+ assert.match(bare.stderr, /--hosts contains unknown value 'console'/);
+ assert.doesNotMatch(bare.stderr, /does not take a value/);
+
+ const valued = runCli('pcf-upgrade.js', ['--apply=1', '--hosts', 'console']);
+ assert.match(valued.stderr, /--apply does not take a value/);
+});
+
+test('pcf-ci-build accepts bare boolean flags and checks them before the selector count', () => {
+ const bare = runCli('pcf-ci-build.js', ['--latest', '--keep', '--all', '--templates']);
+ assert.equal(bare.status, 1);
+ assert.match(bare.stderr, /Choose exactly one of/);
+ assert.doesNotMatch(bare.stderr, /does not take a value/);
+
+ const valued = runCli('pcf-ci-build.js', ['--latest=1', '--all', '--templates']);
+ assert.match(valued.stderr, /--latest does not take a value/);
+});
+
+test('booleanFlagError accepts absent and bare flags and names the first valued flag', () => {
+ assert.equal(booleanFlagError(parseArgs([]).flags, ['a', 'b']), null);
+ assert.equal(booleanFlagError(parseArgs(['--a', '--b']).flags, ['a', 'b']), null);
+ assert.equal(booleanFlagError(parseArgs(['--b=x', '--a=']).flags, ['a', 'b']), '--a does not take a value');
+ assert.equal(booleanFlagError(parseArgs(['--b', 'x']).flags, ['a', 'b']), '--b does not take a value');
+});
diff --git a/plugins/pcf/scripts/tests/pcf-dataverse-real-bundle.test.js b/plugins/pcf/scripts/tests/pcf-dataverse-real-bundle.test.js
index 1b73a0744..b9a06f919 100644
--- a/plugins/pcf/scripts/tests/pcf-dataverse-real-bundle.test.js
+++ b/plugins/pcf/scripts/tests/pcf-dataverse-real-bundle.test.js
@@ -60,7 +60,7 @@ async function sdkWithCapture() {
return { sdk, reads };
}
-test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });
+test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); });
test('REAL BUNDLE: PCF reads record customcontrol query and raw bound-function URLs', async () => {
const { sdk, reads } = await sdkWithCapture();
diff --git a/plugins/pcf/scripts/tests/pcf-dataverse.test.js b/plugins/pcf/scripts/tests/pcf-dataverse.test.js
index e6a55f52f..45ced0a0d 100644
--- a/plugins/pcf/scripts/tests/pcf-dataverse.test.js
+++ b/plugins/pcf/scripts/tests/pcf-dataverse.test.js
@@ -76,7 +76,7 @@ test('makePcfSdk initializes the vendored SDK with the provided workspace and cl
assert.equal(typeof sdk.dataverse.get, 'function');
assert.equal(fs.existsSync(dir), true);
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
diff --git a/plugins/pcf/scripts/tests/pcf-doctor.test.js b/plugins/pcf/scripts/tests/pcf-doctor.test.js
index faa3591a0..49f9605e0 100644
--- a/plugins/pcf/scripts/tests/pcf-doctor.test.js
+++ b/plugins/pcf/scripts/tests/pcf-doctor.test.js
@@ -327,7 +327,7 @@ test('collectProject does not flag complete processed PCF output as stale', () =
assert.equal(ids(findings).includes('PROJ_OUT_STALE'), false);
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -508,7 +508,7 @@ test('collectProject reports unsafe pcfconfig outDir through resolveOutRoot with
assert.match(byId(findings, 'PROJ_OUT_UNSAFE').fix, /pcfconfig\.json/);
assert.match(byId(findings, 'PROJ_OUT_UNSAFE').fix, /out\/controls/);
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -527,7 +527,7 @@ test('collectProject parses UTF-8 BOM package.json while preserving project byte
assert.equal(state.packageJson.devDependencies['pcf-scripts'], dependencySet(MATRIX, 'standard').devDependencies['pcf-scripts']);
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
diff --git a/plugins/pcf/scripts/tests/pcf-gates.test.js b/plugins/pcf/scripts/tests/pcf-gates.test.js
index 53dfc16a6..5f12d8845 100644
--- a/plugins/pcf/scripts/tests/pcf-gates.test.js
+++ b/plugins/pcf/scripts/tests/pcf-gates.test.js
@@ -117,7 +117,7 @@ test('pcf-gates refuses an escaping outDir before a test preparation build can r
assert.equal(fs.readFileSync(path.join(outside, 'sentinel.txt'), 'utf8'), 'keep');
assert.equal(fs.existsSync(path.join(project, 'Control', 'generated', 'ManifestTypes.d.ts')), false);
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
diff --git a/plugins/pcf/scripts/tests/pcf-intent.test.js b/plugins/pcf/scripts/tests/pcf-intent.test.js
index f99accb54..fc27d6175 100644
--- a/plugins/pcf/scripts/tests/pcf-intent.test.js
+++ b/plugins/pcf/scripts/tests/pcf-intent.test.js
@@ -87,7 +87,7 @@ function withRecipeCatalog(recipes, callback) {
}
return callback({ recipesRoot });
} finally {
- fs.rmSync(recipesRoot, { recursive: true, force: true });
+ fs.rmSync(recipesRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
}
@@ -563,7 +563,7 @@ test('write-pcf-plan writes markdown, emits JSON, and exits 1 when lint has erro
assert.ok(payload.findings.some((finding) => finding.code === 'PCF_INTENT_PAGES_NEEDS_WEB'));
assert.match(fs.readFileSync(outPath, 'utf8'), /PCF_INTENT_PAGES_NEEDS_WEB/);
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -580,7 +580,7 @@ test('write-pcf-plan accepts Liquid, writes its instructions, and preserves the
assert.deepEqual(JSON.parse(cli.stdoutText()), { ok: true, out: outPath, findings: [] });
assert.ok(fs.readFileSync(outPath, 'utf8').includes("{% codecomponent name:<registered control name> <property>:'<value>' %}"));
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -600,7 +600,7 @@ test('write-pcf-plan rejects a Pages list journey before writing a plan with sch
assert.match(payload.findings[0].message, /dataset journeys on Power Pages/i);
assert.equal(fs.existsSync(outPath), false);
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -623,7 +623,7 @@ test('write-pcf-plan blocks a Pages dataset while preserving the blocking-plan J
assertFinding(payload.findings, 'PCF_INTENT_PAGES_DATASET', 'error');
assert.match(fs.readFileSync(outPath, 'utf8'), /PCF_INTENT_PAGES_DATASET/);
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -651,7 +651,7 @@ test('write-pcf-plan emits JSON and exits 1 when the intent JSON is invalid', as
assert.equal(payload.ok, false);
assert.match(payload.error, /cannot read PCF intent/);
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -676,7 +676,7 @@ test('write-pcf-plan emits schema JSON instead of throwing for schema-invalid in
assert.ok(payload.findings.some((finding) => finding.code === 'PCF_INTENT_SCHEMA'), name);
assert.match(payload.error, /intent schema is invalid/i, name);
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
}
});
@@ -693,7 +693,7 @@ test('write-pcf-plan rejects a positional intent path without --intent', async (
assert.match(cli.stderrText(), /Usage:/);
assert.equal(cli.stdoutText(), '');
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
diff --git a/plugins/pcf/scripts/tests/pcf-inventory.test.js b/plugins/pcf/scripts/tests/pcf-inventory.test.js
index edd957abc..8fd40f09c 100644
--- a/plugins/pcf/scripts/tests/pcf-inventory.test.js
+++ b/plugins/pcf/scripts/tests/pcf-inventory.test.js
@@ -23,7 +23,7 @@ async function run(argv, stubs) {
}
test.after(() => {
- for (const dir of workspaceDirs) fs.rmSync(dir, { recursive: true, force: true });
+ for (const dir of workspaceDirs) fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
});
test('pcf-inventory excludes managed and first-party controls by default, and --include-managed lifts both filters', async () => {
diff --git a/plugins/pcf/scripts/tests/pcf-lint-cli.test.js b/plugins/pcf/scripts/tests/pcf-lint-cli.test.js
index 91496a1f0..1660f5c00 100644
--- a/plugins/pcf/scripts/tests/pcf-lint-cli.test.js
+++ b/plugins/pcf/scripts/tests/pcf-lint-cli.test.js
@@ -49,7 +49,7 @@ test('lint-pcf fails with structured JSON when a project contains no manifests',
assert.deepEqual(payload.results, []);
assert.match(payload.error, /No ControlManifest\.Input\.xml files were found/);
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
diff --git a/plugins/pcf/scripts/tests/pcf-node-tool.test.js b/plugins/pcf/scripts/tests/pcf-node-tool.test.js
index 8ce515a6f..b8b4b2063 100644
--- a/plugins/pcf/scripts/tests/pcf-node-tool.test.js
+++ b/plugins/pcf/scripts/tests/pcf-node-tool.test.js
@@ -15,7 +15,7 @@ function tmp() {
return d;
}
test.after(() => {
- for (const d of createdDirs) fs.rmSync(d, { recursive: true, force: true });
+ for (const d of createdDirs) fs.rmSync(d, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
});
test('resolvePackageBin reads a string bin', () => {
diff --git a/plugins/pcf/scripts/tests/pcf-push.test.js b/plugins/pcf/scripts/tests/pcf-push.test.js
index 0d50e7e2c..61c61422a 100644
--- a/plugins/pcf/scripts/tests/pcf-push.test.js
+++ b/plugins/pcf/scripts/tests/pcf-push.test.js
@@ -11,7 +11,7 @@ const scriptPath = path.join(__dirname, '..', 'pcf-push.js');
const workspaceRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'pcf-push-workspace-'));
function resetWorkspace() {
- fs.rmSync(workspaceRoot, { recursive: true, force: true });
+ fs.rmSync(workspaceRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
fs.mkdirSync(workspaceRoot, { recursive: true });
}
@@ -90,9 +90,9 @@ async function run(argv, overrides = {}) {
},
...(overrides.requires || {}),
'./lib/pcf-dataverse': {
- makePcfSdk: async (env, workspace) => {
+ makePcfSdk: async (env, workspace, httpClient) => {
calls.push(['makePcfSdk', env, workspace]);
- if (overrides.makePcfSdk) return overrides.makePcfSdk(env, workspace);
+ if (overrides.makePcfSdk) return overrides.makePcfSdk(env, workspace, httpClient);
return { tag: 'sdk' };
},
findCustomControl: async (sdk, name) => {
@@ -147,7 +147,7 @@ function withProcessRunnerStub(stub, fn) {
}
test.beforeEach(resetWorkspace);
-test.after(() => fs.rmSync(workspaceRoot, { recursive: true, force: true }));
+test.after(() => fs.rmSync(workspaceRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
test('happy path forwards exact pac argv, verifies registration, and writes a safe receipt', async () => {
const projectDir = makeProject('happy');
@@ -296,12 +296,16 @@ test('a publish deadlock (SQL 1205) gets a wait-and-retry hint instead of the ge
].join('\n'),
stderr: '',
}),
+ // No Dataverse client can be made (no token), so the publish is not re-sent and pac's failure is reported with its hint.
+ makePcfSdk: () => { throw new Error('az token unavailable'); },
});
assert.equal(cli.exitCode, 1);
const payload = JSON.parse(cli.stdoutText());
assert.equal(payload.ok, false);
assert.equal(payload.stage, 'push');
+ assert.equal(payload.publishAttempts, 1);
+ assert.match(payload.publishRetryError, /az token unavailable/);
assert.equal(payload.hints.length, 1);
assert.match(payload.hints[0], /deadlock victim \(SQL 1205\)/);
// The inventory check needs --env: pcf-inventory.js rejects a call without it, so a hint that
@@ -311,6 +315,167 @@ test('a publish deadlock (SQL 1205) gets a wait-and-retry hint instead of the ge
assert.doesNotMatch(payload.hints[0], /Review the pac pcf push output/);
});
+// The pac output of a push whose import succeeded and whose publish-all step lost a SQL deadlock.
+const DEADLOCK_TEXT = 'Error: Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205';
+const publishDeadlockPac = () => ({
+ status: 1,
+ stdout: ['Importing the temporary solution wrapper into the current org: done.', 'Publishing All Customizations...', DEADLOCK_TEXT].join('\n'),
+ stderr: '',
+});
+// What the transport (lib/dataverse-auth.js makeRequest) resolves for a PublishAllXml: a JSON error answer, a deadlock victim, a success.
+const wireJson = (statusCode, error) => ({ statusCode, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ error }) });
+const deadlockAnswer = () => wireJson(500, { code: '0x80044150', message: ` ${DEADLOCK_TEXT.replace('Error: ', '')}` });
+const publishedAnswer = () => ({ statusCode: 204, headers: {}, body: '' });
+
+// Runs a push whose publish re-send goes through the REAL stack: publishOnceClient, the shared HTTP client (sdk-http-client.js),
+// makePcfSdk and the vendored SDK. Only the token, the transport and the waits are faked. `answers` are the transport's answers to each
+// PublishAllXml in order (the last one repeats), so `posts` is what reached the wire, including any re-send a lower layer would add.
+// Any other request fails the test: the re-send must send nothing but the publish.
+async function runPublishRetry(name, answers, overrides = {}, clientDeps = {}) {
+ const projectDir = makeProject(name);
+ const posts = [];
+ const sleeps = [];
+ const realRetry = require('../lib/pcf-publish-retry.js');
+ const { makePcfSdk } = require('../lib/pcf-dataverse.js');
+ const request = async ({ method, url, body }) => {
+ const pathname = new URL(url).pathname.replace(/^\/api\/data\/v[\d.]+/, '');
+ if (!(method === 'POST' && pathname === '/PublishAllXml')) throw new Error(`unexpected request ${method} ${pathname}`);
+ posts.push([method, pathname, body]);
+ return answers[Math.min(posts.length - 1, answers.length - 1)];
+ };
+ const cli = await run([
+ '--project', projectDir,
+ '--env', 'https://contoso.crm.dynamics.com',
+ '--publisher-prefix', 'abc',
+ ], {
+ runPac: publishDeadlockPac,
+ makePcfSdk: (env, workspace, httpClient) => makePcfSdk(env, workspace, httpClient),
+ requires: {
+ './lib/pcf-publish-retry': {
+ ...realRetry,
+ publishOnceClient: (env) => realRetry.publishOnceClient(env, {
+ getToken: () => 'fake-push-test-token-0123456789',
+ request,
+ sleep: async () => {},
+ ...clientDeps,
+ }),
+ retryPublishAll: (dataverse, opts) => realRetry.retryPublishAll(dataverse, { ...opts, sleep: async (ms) => { sleeps.push(ms); } }),
+ },
+ },
+ ...overrides,
+ });
+ return { cli, projectDir, posts, sleeps };
+}
+
+test('a publish deadlock is re-sent as PublishAllXml once and the push then succeeds without re-running pac', async () => {
+ const { cli, posts, sleeps } = await runPublishRetry('publish-retry-ok', [publishedAnswer()]);
+
+ assert.equal(cli.exitCode, 0);
+ assert.equal(cli.calls.filter((call) => call[0] === 'runPac').length, 1);
+ assert.deepEqual(posts, [['POST', '/PublishAllXml', '{}']]);
+ assert.deepEqual(sleeps, [5000]);
+ const payload = JSON.parse(cli.stdoutText());
+ assert.equal(payload.ok, true);
+ assert.equal(payload.stage, 'done');
+ assert.equal(payload.publishAttempts, 2);
+ assert.deepEqual(payload.registered, { ok: true, version: '1.2.3', expected: '1.2.3' });
+});
+
+test('a publish that keeps deadlocking is sent at most twice more, then fails as before with the attempt count', async () => {
+ const { cli, posts, sleeps } = await runPublishRetry('publish-retry-deadlock', [deadlockAnswer(), deadlockAnswer(), deadlockAnswer()]);
+
+ assert.equal(cli.exitCode, 1);
+ assert.equal(posts.length, 2);
+ assert.deepEqual(sleeps, [5000, 15000]);
+ const payload = JSON.parse(cli.stdoutText());
+ assert.equal(payload.ok, false);
+ assert.equal(payload.stage, 'push');
+ assert.equal(payload.status, 1);
+ assert.equal(payload.publishAttempts, 3);
+ assert.equal(payload.publishRetryError, undefined);
+ assert.equal(payload.hints.length, 1);
+ assert.match(payload.hints[0], /deadlock victim \(SQL 1205\)/);
+ assert.equal(cli.calls.some((call) => call[0] === 'findCustomControl'), false);
+});
+
+test('a re-sent publish answered with another error is not sent again', async () => {
+ const uniqueKey = wireJson(500, { code: '0x80044150', message: 'Sql error: duplicate key (Sql Number: 1205). CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 2627' });
+ const { cli, posts } = await runPublishRetry('publish-retry-other', [uniqueKey, publishedAnswer()]);
+
+ assert.equal(cli.exitCode, 1);
+ assert.equal(posts.length, 1);
+ const payload = JSON.parse(cli.stdoutText());
+ assert.equal(payload.stage, 'push');
+ assert.equal(payload.publishAttempts, 2);
+ assert.match(payload.publishRetryError, /^HTTP 500: .*Sql Number: 2627$/);
+});
+
+test('a re-sent publish whose answer was lost is not sent again', async () => {
+ const lost = { error: 'socket hang up', code: 'ECONNRESET' };
+ const { cli, posts } = await runPublishRetry('publish-retry-lost', [lost, publishedAnswer()]);
+
+ assert.equal(cli.exitCode, 1);
+ assert.equal(posts.length, 1);
+ const payload = JSON.parse(cli.stdoutText());
+ assert.equal(payload.stage, 'push');
+ assert.equal(payload.publishAttempts, 2);
+ assert.match(payload.publishRetryError, /socket hang up/);
+});
+
+test('a SQL 1205 before the publish step, or any other push failure, is never re-sent', async () => {
+ for (const [label, stdout] of [
+ ['import deadlock', ['Importing the temporary solution wrapper into the current org...', DEADLOCK_TEXT].join('\n')],
+ ['other publish error', ['Publishing All Customizations...', 'Error: Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 2627'].join('\n')],
+ ['tool failure', 'Missing required tool dotnet'],
+ ]) {
+ const { cli, posts } = await runPublishRetry(`publish-no-retry-${slugOf(label)}`, [publishedAnswer()], {
+ runPac: () => ({ status: 1, stdout, stderr: '' }),
+ });
+ assert.equal(cli.exitCode, 1, label);
+ assert.equal(posts.length, 0, label);
+ assert.equal(cli.calls.some((call) => call[0] === 'makePcfSdk'), false, label);
+ const payload = JSON.parse(cli.stdoutText());
+ assert.equal(payload.stage, 'push', label);
+ assert.equal(Object.prototype.hasOwnProperty.call(payload, 'publishAttempts'), false, label);
+ }
+});
+
+// The shared HTTP client re-sends a publish refused with a 401 (after a token refresh) or a service-protection 429 on its own; under the
+// deadlock re-send that would multiply the sends behind one reported attempt. Each answer must reach the wire exactly once.
+for (const [label, answer, pattern] of [
+ ['service-protection 429', { ...wireJson(429, { code: '0x80072322', message: 'Number of requests exceeded the limit of 6000 over time window of 300 seconds.' }), headers: { 'content-type': 'application/json', 'retry-after': '1' } }, /^HTTP 429: Number of requests exceeded/],
+ ['401', wireJson(401, { code: '0x80072560', message: 'The user is not a member of the organization.' }), /^HTTP 401/],
+]) {
+ test(`a re-sent publish answered ${label} is sent exactly once and reported as two attempts`, async () => {
+ const { cli, posts, sleeps } = await runPublishRetry(`publish-retry-${slugOf(label)}`, [answer, publishedAnswer()]);
+
+ assert.equal(cli.exitCode, 1, label);
+ assert.equal(posts.length, 1, label);
+ assert.deepEqual(sleeps, [5000], label);
+ const payload = JSON.parse(cli.stdoutText());
+ assert.equal(payload.stage, 'push', label);
+ assert.equal(payload.publishAttempts, 2, label);
+ assert.match(payload.publishRetryError, pattern, label);
+ });
+}
+
+test('a re-send that never reached the wire (no token) is not counted as an attempt', async () => {
+ const { cli, posts } = await runPublishRetry('publish-retry-no-token', [publishedAnswer()], {}, {
+ getToken: () => { throw new Error('az token unavailable'); },
+ });
+
+ assert.equal(cli.exitCode, 1);
+ assert.equal(posts.length, 0);
+ const payload = JSON.parse(cli.stdoutText());
+ assert.equal(payload.stage, 'push');
+ assert.equal(payload.publishAttempts, 1);
+ assert.match(payload.publishRetryError, /az token unavailable/);
+});
+
+function slugOf(label) {
+ return label.replace(/\W+/g, '-');
+}
+
test('push refusal from process-runner emits one JSON error through the real pac adapter', async () => {
const projectDir = makeProject('runner-refusal');
const refusal = Object.assign(new Error('cannot pass "%" to pac.cmd: a Windows batch file cannot receive % unchanged'), { code: 'EARGUMENT' });
diff --git a/plugins/pcf/scripts/tests/pcf-scaffold.test.js b/plugins/pcf/scripts/tests/pcf-scaffold.test.js
index 0c838bff7..8991c7551 100644
--- a/plugins/pcf/scripts/tests/pcf-scaffold.test.js
+++ b/plugins/pcf/scripts/tests/pcf-scaffold.test.js
@@ -86,7 +86,7 @@ test('listRecipes and renderRecipesTable handle an empty recipe catalog', () =>
'',
].join('\n'));
} finally {
- fs.rmSync(recipesRoot, { recursive: true, force: true });
+ fs.rmSync(recipesRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -379,7 +379,7 @@ test('listRecipes rejects malformed recipe metadata with clear validation errors
assert.throws(() => listRecipes({ recipesRoot: root }), /recipe\.json: id must equal directory name 'broken'; title must be a non-empty string; summary must be a non-empty string; template must be an existing template id; hosts must be a non-empty array containing only template hosts; whyWanted must be a non-empty string; certified\.model\.field must be YYYY-MM-DD; certified\.pages must be an object; configuration must be a non-empty string; properties\[0\]\.name must be a non-empty string; properties\[0\]\.displayNameKey must be a non-empty string; properties\[0\]\.descriptionKey must be a non-empty string; properties\[0\]\.ofType must be a non-empty string; properties\[0\]\.usage must be bound, input, or output; properties\[0\]\.required must be boolean/);
} finally {
- fs.rmSync(root, { recursive: true, force: true });
+ fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -405,7 +405,7 @@ test('listRecipes rejects planned recipe metadata without explicit certification
/recipe\.json: certified must be \{ "model": \{\}, "pages": \{\} \} or host journey date maps/,
);
} finally {
- fs.rmSync(root, { recursive: true, force: true });
+ fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -510,7 +510,7 @@ test('listTemplates rejects malformed template metadata before exposing the cata
assert.throws(() => listTemplates({ root }), /template\.json.*controlType/);
} finally {
- fs.rmSync(root, { recursive: true, force: true });
+ fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -766,7 +766,7 @@ test('writeScaffold refuses a non-empty output directory', () => {
fs.writeFileSync(path.join(dir, 'keep.txt'), 'existing');
assert.throws(() => writeScaffold(renderFieldPlan(), dir), /exists and is not empty/);
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -777,7 +777,7 @@ test('writeScaffold reports an existing PCF project before the generic non-empty
fs.writeFileSync(path.join(dir, 'package.json'), '{}');
assert.throws(() => writeScaffold(renderFieldPlan(), dir), /already contains a PCF project/);
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -789,7 +789,7 @@ test('writeScaffold rejects unsafe planned relative paths', () => {
try {
assert.throws(() => writeScaffold({ files: [{ relPath, content: 'bad' }], warnings: [] }, dir), /unsafe scaffold path/);
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
}
});
@@ -803,7 +803,7 @@ test('writeScaffold allows safe nested planned relative paths', () => {
assert.deepEqual(result.written, [path.join(dir, 'nested', 'ok.txt')]);
assert.equal(fs.readFileSync(path.join(dir, 'nested', 'ok.txt'), 'utf8'), 'ok');
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -817,7 +817,7 @@ test('writeScaffold writes a complete project into an empty directory', () => {
assert.ok(fs.existsSync(path.join(dir, 'StarRating', 'index.ts')));
assert.ok(fs.existsSync(path.join(dir, 'test', 'pcf-context.ts')));
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -866,7 +866,7 @@ test('CLI scaffolds and threads --npm-cli into --install', () => {
// macOS resolves /var to /private/var. Native realpath matches both; JS realpath keeps 8.3 names.
assert.deepEqual(JSON.parse(fs.readFileSync(log, 'utf8')), { argv: ['ci'], cwd: fs.realpathSync.native(outDir) });
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -903,7 +903,7 @@ test('writeScaffold reports info and writes through a directory link to the phys
assert.match(finding.message, new RegExp(escapeRegExp(path.resolve(requested))));
assert.match(finding.message, new RegExp(escapeRegExp(physical)));
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -931,7 +931,7 @@ test('writeScaffold refuses a non-empty physical directory reached through a lin
assert.equal(fs.existsSync(path.join(physical, 'StarRating.pcfproj')), false);
assert.equal(fs.readFileSync(path.join(physical, 'keep.txt'), 'utf8'), 'existing');
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -955,7 +955,7 @@ test('writeScaffold has no redirect finding for native canonicalization without
assert.equal(fs.readFileSync(path.join(result.resolvedOutDir, 'marker.txt'), 'utf8'), 'ok');
assert.equal(fs.existsSync(path.join(outDir, 'marker.txt')), false, 'writes must still use native realpath');
} finally {
- fs.rmSync(parent, { recursive: true, force: true });
+ fs.rmSync(parent, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -970,7 +970,7 @@ test('writeScaffold has no redirect finding when the output path is already phys
assert.deepEqual(result.findings, []);
assert.equal(fs.readFileSync(path.join(outDir, 'marker.txt'), 'utf8'), 'ok');
} finally {
- fs.rmSync(parent, { recursive: true, force: true });
+ fs.rmSync(parent, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -1010,6 +1010,6 @@ test('CLI reports resolvedOutDir and redirect info when --out goes through a lin
assert.match(finding.message, new RegExp(escapeRegExp(physicalOut)));
assert.equal(fs.existsSync(path.join(physicalOut, 'StarRating.pcfproj')), true);
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
diff --git a/plugins/pcf/scripts/tests/pcf-upgrade.test.js b/plugins/pcf/scripts/tests/pcf-upgrade.test.js
index 9505b9fe0..f2525ff57 100644
--- a/plugins/pcf/scripts/tests/pcf-upgrade.test.js
+++ b/plugins/pcf/scripts/tests/pcf-upgrade.test.js
@@ -406,7 +406,7 @@ test('CLI rejects explicit empty --steps selections without changing any project
assert.match(result.stderr, /Usage:/);
assert.match(result.stderr, /--steps (?:must include at least one step id|requires a value)/);
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
}
});
@@ -430,7 +430,7 @@ test('runUpgrade limits apply to selected steps and rejects unknown step ids', (
assert.equal(unknown.ok, false);
assert.match(unknown.error, /Unknown --steps value 'UNKNOWN_STEP'/);
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -449,7 +449,7 @@ test('runUpgrade applies relative to the discovered project root when started fr
assert.deepEqual(result.changedFiles, [path.join(projectDir, 'package.json')]);
assert.doesNotMatch(String(result.error || ''), /outside the PCF project/);
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -468,7 +468,7 @@ test('runUpgrade can collect and apply a UTF-8 BOM package.json without dropping
const after = fs.readFileSync(packagePath, 'utf8');
assert.equal(after.charCodeAt(0), 0xFEFF);
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -495,7 +495,7 @@ test('runUpgrade refuses a dirty git tree before applying changes', () => {
assert.match(result.error, /uncommitted changes/);
assert.deepEqual(result.applied, []);
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -534,7 +534,7 @@ test('runUpgrade refuses apply outside a git work tree unless allowDirty is pass
assert.equal(allowed.ok, true);
assert.ok(allowed.applied.includes('DEPS_TO_MATRIX'));
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -560,7 +560,7 @@ test('runUpgrade reports a failing transform without writing earlier computed fi
assert.equal(result.after, null);
assert.equal(fs.readFileSync(pkg, 'utf8'), beforePackage);
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -585,7 +585,7 @@ test('applyUpgrade computes all transforms before writing any file', () => {
assert.equal(fs.readFileSync(pkg, 'utf8'), '{"name":"before"}\n');
assert.equal(fs.readFileSync(proj, 'utf8'), '<Project />\n');
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -641,7 +641,7 @@ test('applyUpgrade restores every target when a writer truncates then throws', (
run(afterPkg);
run(afterProj);
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -685,7 +685,7 @@ test('applyUpgrade rolls back earlier writes when a later write fails', () => {
assert.equal(fs.readFileSync(pkg, 'utf8'), '{"name":"before"}\n');
assert.equal(fs.readFileSync(proj, 'utf8'), '<Project />\n');
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -712,7 +712,7 @@ test('applyUpgrade refuses a project file symlink that resolves outside the proj
}, projectDir), /outside the PCF project/);
assert.equal(fs.readFileSync(outsidePackage, 'utf8'), '{"name":"outside"}\n');
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -745,7 +745,7 @@ test('applyUpgrade writes a project reached through a linked parent directory',
assert.deepEqual(result.applied, ['DEPS_TO_MATRIX']);
assert.equal(fs.readFileSync(path.join(projectReal, 'package.json'), 'utf8'), '{"name":"after"}\n');
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -775,7 +775,7 @@ test('runUpgrade rolls back every rewritten file when reinstall fails after safe
assert.deepEqual(fs.readFileSync(pkg), originalPackage);
assert.equal(result.after, null);
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -814,7 +814,7 @@ test('applyUpgrade restores the lockfile a failed reinstall rewrote and removes
if (hadLockfile) assert.deepEqual(fs.readFileSync(lock), originalLock);
else assert.equal(fs.existsSync(lock), false, 'a lockfile the failed install created is removed');
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
}
});
@@ -853,7 +853,7 @@ test('applyUpgrade writes safe files, runs npm install, and skips install when r
const skipped = applyUpgrade({ steps: [{ id: 'REINSTALL' }] }, projectDir, { noInstall: true });
assert.deepEqual(skipped.skipped, ['REINSTALL: run npm install in the PCF project']);
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -899,7 +899,7 @@ test('runUpgrade accepts --steps REINSTALL alone', () => {
const reinstall = result.plan.steps.find((step) => step.id === 'REINSTALL');
assert.equal(reinstall.requiresStep, null);
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -923,7 +923,7 @@ test('runUpgrade records the skipped reinstall when --steps REINSTALL is used wi
assert.deepEqual(result.applied, []);
assert.deepEqual(result.skipped, ['REINSTALL: run npm install in the PCF project']);
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -949,7 +949,7 @@ test('selecting DEPS_TO_MATRIX still reinstalls and publishes requiresStep', ()
assert.equal(reinstall.requiresStep, null);
assert.ok(result.plan.steps.every((step) => Object.hasOwn(step, 'requiresStep')));
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -970,7 +970,7 @@ test('selecting DEPS_TO_MATRIX and REINSTALL installs once', () => {
assert.equal(npm.calls.length, 1);
assert.equal(result.plan.steps.filter((step) => step.id === 'REINSTALL').length, 1);
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
@@ -990,6 +990,6 @@ test('unknown --steps lists every selectable id including REINSTALL', () => {
assert.match(result.error, /Choose one of: .*REINSTALL/);
assert.match(result.error, /DEPS_TO_MATRIX/);
} finally {
- fs.rmSync(tmp, { recursive: true, force: true });
+ fs.rmSync(tmp, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
diff --git a/plugins/pcf/scripts/tests/pcf-verify-cli.test.js b/plugins/pcf/scripts/tests/pcf-verify-cli.test.js
index 6410bfe64..ddd4d1afe 100644
--- a/plugins/pcf/scripts/tests/pcf-verify-cli.test.js
+++ b/plugins/pcf/scripts/tests/pcf-verify-cli.test.js
@@ -296,7 +296,7 @@ test('verify-pcf rejects intent bindings whose client list normalizes to empty b
assert.equal(madeSdk, false);
assert.equal(cli.stdoutText(), '');
} finally {
- fs.rmSync(dir, { recursive: true, force: true });
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
diff --git a/plugins/pcf/scripts/tests/validate-write-safety.test.js b/plugins/pcf/scripts/tests/validate-write-safety.test.js
index b90ad55c3..ab8d25c30 100644
--- a/plugins/pcf/scripts/tests/validate-write-safety.test.js
+++ b/plugins/pcf/scripts/tests/validate-write-safety.test.js
@@ -55,7 +55,7 @@ test.beforeEach(() => {
fs.writeFileSync(path.join(cwd, 'pcf-plan.md'), '# plan\n', 'utf8');
});
test.afterEach(() => {
- try { fs.rmSync(cwd, { recursive: true, force: true }); } catch { /* ignore */ }
+ try { fs.rmSync(cwd, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); } catch { /* ignore */ }
});
test('write inside the working directory is allowed (exit 0)', () => {
diff --git a/plugins/pcf/templates/dataset-virtual/__tests__/{{name}}.test.ts.tmpl b/plugins/pcf/templates/dataset-virtual/__tests__/{{name}}.test.ts.tmpl
index 767673dde..eee9e90a0 100644
--- a/plugins/pcf/templates/dataset-virtual/__tests__/{{name}}.test.ts.tmpl
+++ b/plugins/pcf/templates/dataset-virtual/__tests__/{{name}}.test.ts.tmpl
@@ -197,3 +197,11 @@ test("opens records through openDatasetItem", () => {
expect(ds.openDatasetItem).toHaveBeenCalledWith(expect.objectContaining({ id: "first" }));
});
+
+test("open and paging actions render as Fluent v9 buttons", () => {
+ const { buttons } = render(dataSet({ hasNextPage: true, hasPreviousPage: true }));
+
+ // fui-Button is the stable class Fluent v9 puts on every Button root.
+ expect(buttons().length).toBe(4);
+ expect(buttons().every((button) => button.classList.contains("fui-Button"))).toBe(true);
+});
\ No newline at end of file
diff --git a/plugins/pcf/templates/dataset-virtual/{{name}}/css/{{name}}.css.tmpl b/plugins/pcf/templates/dataset-virtual/{{name}}/css/{{name}}.css.tmpl
index e3b6c231e..c29e4805c 100644
--- a/plugins/pcf/templates/dataset-virtual/{{name}}/css/{{name}}.css.tmpl
+++ b/plugins/pcf/templates/dataset-virtual/{{name}}/css/{{name}}.css.tmpl
@@ -15,10 +15,6 @@
padding: 0.375rem 0.5rem;
}
-.{{cssClass}} button {
- min-height: 2rem;
-}
-
.{{nameLower}}-pager {
display: flex;
gap: 0.5rem;
diff --git a/plugins/pcf/templates/dataset-virtual/{{name}}/{{name}}View.tsx.tmpl b/plugins/pcf/templates/dataset-virtual/{{name}}/{{name}}View.tsx.tmpl
index b52f4c44f..90ca29138 100644
--- a/plugins/pcf/templates/dataset-virtual/{{name}}/{{name}}View.tsx.tmpl
+++ b/plugins/pcf/templates/dataset-virtual/{{name}}/{{name}}View.tsx.tmpl
@@ -1,4 +1,7 @@
import * as React from "react";
+// Fluent v9 Button comes from the declared Fluent platform library, so it is not bundled and
+// follows the host theme; it renders a native <button>, so disabled and aria-label behave as before.
+import { Button } from "@fluentui/react-components";
type DataSetRecord = ComponentFramework.PropertyHelper.DataSetApi.EntityRecord;
@@ -87,7 +90,7 @@ function row(
return React.createElement("tr", { key: id },
React.createElement("td", null, text),
React.createElement("td", null,
- React.createElement("button", {
+ React.createElement(Button, {
type: "button",
"aria-label": props.openRecordLabel.replace("{0}", text),
onClick: () => props.onOpenRecord(record),
@@ -106,12 +109,12 @@ function pager(
): React.ReactElement {
const busy = props.busy || dataSet.loading === true;
return React.createElement("div", { className: "{{nameLower}}-pager" },
- React.createElement("button", {
+ React.createElement(Button, {
type: "button",
disabled: busy || !dataSet.paging.hasPreviousPage,
onClick: props.onPreviousPage,
}, "Previous"),
- React.createElement("button", {
+ React.createElement(Button, {
type: "button",
disabled: busy || !dataSet.paging.hasNextPage,
onClick: props.onNextPage,
diff --git a/plugins/pcf/templates/field-virtual/__tests__/{{name}}.test.ts.tmpl b/plugins/pcf/templates/field-virtual/__tests__/{{name}}.test.ts.tmpl
index 3ae6c5af1..abd2fc99a 100644
--- a/plugins/pcf/templates/field-virtual/__tests__/{{name}}.test.ts.tmpl
+++ b/plugins/pcf/templates/field-virtual/__tests__/{{name}}.test.ts.tmpl
@@ -102,3 +102,26 @@ test("two instances keep independent state and DOM", () => {
expect(second.control.getOutputs()).toEqual({ sampleProperty: "Second" });
expect(first.container.querySelector(".{{cssClass}}") === second.container.querySelector(".{{cssClass}}")).toBe(false);
});
+
+test("the field renders a Fluent v9 Input bound to the value", () => {
+ const { container, input } = render({ sampleProperty: mockProperty("Existing") as IInputs["sampleProperty"] });
+ const wrapper = container.querySelector(".fui-Input") as HTMLElement;
+
+ // fui-Input is the stable class Fluent v9 puts on every Input root.
+ expect(wrapper.contains(input())).toBe(true);
+ expect(input().value).toBe("Existing");
+ expect(wrapper.hidden).toBe(false);
+ expect(wrapper.style.display).toBe("");
+});
+
+test("unreadable security hides the Fluent Input wrapper too", () => {
+ const { container } = render({
+ sampleProperty: mockProperty("Hidden", undefined, { readable: false }) as IInputs["sampleProperty"],
+ });
+ const wrapper = container.querySelector(".fui-Input") as HTMLElement;
+
+ expect(wrapper.hidden).toBe(true);
+ // Fluent's own class gives the wrapper `display: inline-flex`, which overrides the browser's
+ // `[hidden]` rule, so the attribute alone would leave an empty bordered box on screen.
+ expect(wrapper.style.display).toBe("none");
+});
\ No newline at end of file
diff --git a/plugins/pcf/templates/field-virtual/{{name}}/css/{{name}}.css.tmpl b/plugins/pcf/templates/field-virtual/{{name}}/css/{{name}}.css.tmpl
index 66878e52a..9fa0644b7 100644
--- a/plugins/pcf/templates/field-virtual/{{name}}/css/{{name}}.css.tmpl
+++ b/plugins/pcf/templates/field-virtual/{{name}}/css/{{name}}.css.tmpl
@@ -6,9 +6,7 @@
}
.{{cssInputClass}} {
- box-sizing: border-box;
- min-height: 2rem;
- padding: 0.25rem 0.5rem;
+ width: 100%;
}
.{{cssMessageClass}} {
diff --git a/plugins/pcf/templates/field-virtual/{{name}}/{{name}}View.tsx.tmpl b/plugins/pcf/templates/field-virtual/{{name}}/{{name}}View.tsx.tmpl
index acdbf7640..3d8d93b42 100644
--- a/plugins/pcf/templates/field-virtual/{{name}}/{{name}}View.tsx.tmpl
+++ b/plugins/pcf/templates/field-virtual/{{name}}/{{name}}View.tsx.tmpl
@@ -1,4 +1,5 @@
import * as React from "react";
+import { Input, InputOnChangeData } from "@fluentui/react-components";
export interface {{name}}ViewProps {
cssClass: string;
@@ -17,15 +18,22 @@ export function {{name}}View(props: {{name}}ViewProps): React.ReactElement {
return React.createElement(
"div",
{ className: props.cssClass },
- React.createElement("input", {
+ // Fluent v9 Input comes from the declared Fluent platform library, so it is not bundled
+ // and it follows the host theme. Native input props (aria-label, disabled, readOnly,
+ // hidden, value) land on the inner <input>; className and root props land on the wrapper.
+ // The wrapper's Fluent class sets `display: inline-flex`, which overrides the browser's
+ // `[hidden]` rule, so a hidden wrapper also gets an inline `display: none`; without it an
+ // empty bordered box would stay on screen when field security hides the value.
+ React.createElement(Input, {
"aria-label": props.label,
className: props.inputClass,
+ root: { hidden: props.hidden, style: props.hidden ? { display: "none" } : undefined },
disabled: props.disabled,
hidden: props.hidden,
readOnly: props.readOnly,
type: "text",
value: props.value,
- onChange: (event: React.ChangeEvent<HTMLInputElement>) => props.onChange(event.currentTarget.value),
+ onChange: (_event: React.ChangeEvent<HTMLInputElement>, data: InputOnChangeData) => props.onChange(data.value),
}),
React.createElement("div", { className: props.messageClass, hidden: !props.message }, props.message),
);