A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
model-apps 2.24.0: show or hide existing command buttons by row id (#834)
Akshay Maloo6422d3ea90b9
diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex 6ed55e112..9a839a8dc 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.23.0",+ "version": "2.24.0","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.jsonindex 6ed55e112..9a839a8dc 100644--- a/plugins/model-apps/.plugin/plugin.json+++ b/plugins/model-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.23.0",+ "version": "2.24.0","description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.","author": {"name": "Microsoft",diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.mdindex c18665f1d..6ea6eef07 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -3585,6 +3585,143 @@ SDK reads some joined-table columns back without their join; a declared column crefused (`view-related-column-unrepresentable`). A chart title can be written only to a chart thatalready has one.+### Command states (`commandStates[]`, 2.24.0)++Sets the stored `hidden` / `isdisabled` flags of existing table-scoped modern command rows (`appaction`), picked by+row id from `list-command-states.js`. It is not a reconcile of `commands[]`: the two never share an entry, legacy+`commands[]` edits are still not applied, and keyed `commands[]` in the same spec is refused+(`command-state-keyed-unsupported`). Spec contract and maker workflow: `references/app-spec-schema-advanced.md`.++- **Engine-boundary check**: `runSdkBuild` first runs the App Spec's own offline check (`commandStateSpecHalt`),+ before the lease, the mode choice or any request, so a direct caller or a structural-profile run (where these+ findings are only warnings) cannot skip it: app scope is `command-state-app-scope-unverified`, any other invalid+ value (`null` included; only absent or `[]` means none) is `command-state-spec-invalid`.+- **Flow** (`lib/command-state-run.js`, wired in `sdk-build.js`): `commandStateMode` refuses any apply that is not+ a full build with `--publish` before anything is read (exactly `--stage data` leaves them alone; a dry run plans+ them read-only and prints every token). Each attempt's earliest preflight — before the build's first write —+ resolves the app context, reads every declared row with the shared decoder and checks the exact approvals+ (`overwrite:command-state:…` per changed row version, `publish:command-state-table:…` per declared table). The+ commands phase re-reads each row and sends one conditional flag-only PATCH per changed row. A refusal or unknown+ outcome is a `BuildHalt` with `retry: never`: a lost answer is never resent (`command-state-write-unknown`), and an+ ordinary retry of another halt starts a new attempt that re-reads and re-plans.+- **Approval tokens stay off disk.** An approval halt's message names what is missing but not the token; the exact+ `--authorize` lines ride on the halt as non-enumerable `approvalDisplay` (`withApprovalDisplay`), which the CLI prints+ to the console only, so `build-log.jsonl` and `build-status.json` never hold a token or digest.+- **Raw-request exception.** The SDK has no update of an `appaction` row's flags, so the row PATCH goes through+ `command-state-transport.js` `patchRow` on a raw az-token client `makeSdk` creates only for a spec that declares+ `commandStates`, behind the same publication barrier and write gate, sent once (`commandStateSendOnce`).+- **Publication** adds no SDK push and no second publish request. `publishTablesBeforeApp` unions the declared tables+ into its existing before-app set; the one publication observer per invocation records whether that plain+ request, or the managed publisher's flush for a managed table (the supported overlap: the existing publisher+ publishes it, the observer reads its `published` list), named each table after its latest row write. The managed+ publisher publishes one routed table at a time and throws on the first it cannot; before it throws, its flush tells+ an optional `onHalt` what it settled (`published`, `withheld`, and `failed`: the table whose publish was attempted+ and not confirmed - the request may or may not have been sent), so a table published before the halt is reported+ confirmed and the failing one `failed`, never as confirmed and never as untouched.+ `onHalt` is only told: the halt thrown is the publisher's own, whatever it does. An apply+ succeeds only when both final checks pass. First, after the build's app work, every declared row is judged against+ a freshly resolved app context (the commands phase's context is not membership proof) and must still hold its+ flags; a failure keeps its own code, `command-state-context-unverified` or `command-state-not-confirmed` (a row+ that no longer matches is worded from what this run did to it, never as an accepted write it did not make), and+ rolls nothing back. That check reads every declared row once, even after one has failed, and notes each read in the+ row's facts; the halt is the first failure's (its code, retry policy and wording), followed by each later failure.+ Second, every declared table must be confirmed published; only that failure halts with+ `command-state-publish-unconfirmed` (worded per table from its rows' facts: saved / held after a write with no+ usable answer / already held / held other flags at its last read / could not be read at its last read / write+ outcome unknown / not written). A reconciled table the plain request did not publish (it was refused, or there is+ no raw client to send it) is published by the SDK (`publishReconciledTables`), and that publication confirms it only+ when the SDK's answer proves a request was sent and succeeded — kind `submitted`, `verified` or `unverifiable`+ (`publishAnswerProvesPublication`, `managed-feature-contract.js`; path `sdk-before-app`). A no-request kind (`none`,+ `notApplicable`, `notRequested`), an unknown kind or no kind proves nothing and leaves it unconfirmed; one the SDK+ refuses stays unconfirmed and halts before the app as before. **Every table publication goes through one helper**,+ `createTablePublication` (`sdk-build.js`), which tells the observer what it published, with the path that names+ the call site: the plain envelope (`plain-before-app`), every managed flush (`managed-before-app`,+ `managed-views-phase`, `managed-reconcile`, `managed-app-publication`, `managed-publish-phase`,+ `managed-end-of-build`, each with its partial result on a halt), the reconciled fallback (`sdk-before-app`), a+ reconcile's or the app publication's own table publish (`sdk-reconcile`, `sdk-app-publication`) and the publish+ phase's SDK publication (`sdk-publish-phase`). The first publication seen after a table's latest row write is the+ one recorded. The SDK publication tells the observer of each table **as its answer proves it** (`publishTargets`'+ `onProven`), not once the call returns, so a later target that throws — the real SDK's `ARTIFACT_NOT_FOUND`+ preflight of an artifact its workspace does not hold, a retry, or the single-target pass after a batch that threw —+ does not take back a table already proven; a partial or failed batch confirms nothing. An SDK answer confirms a table only when it proves a request (as above) **and its `publishScope` is+ that table's own `entity` envelope**: the vendored SDK publishes a view, chart, form or table-bound dashboard as+ `<entities><entity>t</entity></entities>` and answers `publishScope: { envelope: 'entity', entityLogicalName: 't' }`+ (also per artifact of one batch), while an unbound dashboard (`dashboard`) and the app (`appmodule`) name no table+ and confirm none. A source inventory in `command-state-publication-build.test.js` fails on a table publication in+ `sdk-build.js` outside the helper (the app's own publish in `appWriters` is the one listed exception). In a build+ with `commandStates`, every warning, halt and journal line about a failed table publication says only its checked+ facts (`publish-refused`: status, Dataverse code, system code) — the SDK's refusal of the fallback, its settle after+ a final halt (`settleOwedPublishes` with `checked`), the publish phase's, and a managed publish whose client failed+ before dispatch (the managed publisher's `sayRefusal`) — while the structured error that decides a retry is kept.+ An error a table publication **throws** (phase 8 or the reconciled fallback) is thrown on unchanged — its message,+ code, cause and status still decide the retry — and carries a non-enumerable mark (`withCheckedDisplay`,+ `command-state-contract.js`) that the runner's halt and journal line say instead of its message (`checkedDisplay`+ in `makeRunner`), with its code kept only when it has a system code's shape. After a final halt, a failed read of+ what is still saved and not published (`readSavedNotPublished` with `facts`) is said as that read, by its label and+ checked facts (`describeSavedNotPublished` with `checked`); what a read that succeeded found is listed the same way+ either way. A build without `commandStates` prints, journals and decides exactly as before. Every message that words a row after its step (that publication halt, the+ post-write read, the final drift and late membership checks, a retry's approval halt, the CLI's result lines) words+ it from the row's **facts** — an ordered, append-only list of what each read found (matched, other flags, or could+ not be read, with the phase it was made in) and how each write was answered — through one renderer,+ `renderRowHistory`, and one publication kind, `rowKind`, composed only of the vocabulary in `lib/command-state-run.js`+ (`ROW_PHRASES`, `READ_PHASES`, `KINDS`). Only a write answered 200/204 and then read back holding the flags is said+ to be accepted or saved; a write with no usable answer says its outcome is unknown and what a later read found; a row+ this build did not write says so; a read that could not be judged says only that. The facts hold no version, token+ or service text, and outlive the build's own retries (the publication observer owns them), so a retry tags each+ clause with its attempt and never says "not written by this build" of a row an earlier attempt wrote; a row whose+ later attempt has nothing to send keeps the earlier write's outcome while every read since it matched. The outcome+ (`ROW_OUTCOMES`) is a short name for the row's step: `record` passes it through `checkRowRecord`, which throws on any+ value the list does not name or the row's facts do not show. `command-state-outcomes.test.js` checks every history+ of facts on every path, including a real final-proof halt that sent no write, and keeps a case-insensitive+ literal-text inventory: it lexes the string, template and regular-expression literals of the writer's sources+ (`lib/source-literals.js`) and fails on a listed claim word (accept, acknowledge, save, outcome unknown, written by+ this build, with the inflections it lists) outside the vocabulary. The inventory reads literal text only — no+ constant folding or call-graph analysis — so wording built at run time is left to the behavioural tests on the+ actual messages. Any such+ halt carries non-enumerable `commandStates` and, while a table's publication is unconfirmed,+ `commandStatePublicationError` (never in the journal or a retry's reading).+ There is no store and no cross-run fence: a sent publish can complete after a halt or after an entry is removed,+ and the next publishing run requests the table only because the spec still names it. Existing managed-artifact+ fences still apply on their own.+- **Shared decoder contract** (`command-state-read.js`): a missing column is not a null and a null flag is not+ `false`; static visibility is a present `visibilitytype` of null or 0 with every visibility-formula column present+ and empty (the null `commands[]` leaves is static); `visibilitytype` is never written; only a table-scoped row is a+ candidate. **Service answers are worded by one formatter**, `serviceAnswerText` (`command-state-contract.js`), from+ checked values only: the HTTP status (an integer), the Dataverse error code (`0x` and eight hex digits, else+ dropped), the system code of a read with no answer (`ECONNRESET`: capitals, digits and `_`, else dropped), a+ problem from the fixed `SERVICE_PROBLEMS` list and field names from the fixed `SERVICE_FIELDS` list — never the+ service's message, a link, a value or a row version, so `0x80040220` is said and the message beside it is not. These+ paths word a failed or malformed answer through it, and through nothing else: the context reads (`as` in+ `command-state-read.js` for the app, components, table and listing reads; the current layer; a table by metadata id;+ `IsOptimisticConcurrencyEnabled`), the row read (`readCommandStateRow`), `readFailureText` (a thrown read error, used+ by verify's details and a lost write's cause), the transport's refusal of a continuation outside the API, a+ refused row write (`command-state-run.js`, `write-refused`), and the before-app table publish's refusal warning+ (`publish-refused`: `publishTablesXml` with `facts: true` returns the status, Dataverse code or system code beside+ its reason), and every other failed table publication of such a build (`createTablePublication`, above). The shared reader (`collectionRows`) still copies the+ service's message and value into the errors it throws, and the publish warning of a build without `commandStates`+ still quotes the reason, so such a build prints what it always printed; this feature never says them: a refused+ read is said from the answer itself (`watched`), and a complaint+ about a 2xx answer is matched to the problem it names (`complaintOf`), the rest being `unexpected`. The transport's+ other refusals are fixed text that names no path or row version. The one service text a maker is shown is a+ button's caption (`buttonlabeltext`), as the inventory and approval require: the listing's `commands[].caption`,+ the approval display and the dry-run plan (console only); a halt and the journal name the row by table, bar and+ row id, without it. `command-state-taint.test.js` is the class gate: it plants one marker shaped like a row+ version into each string position (error code and message, next-page links, `value`, each field) of each answer+ the feature reads, in each phase (preflight, final proof, the row write, the listing, verify), and into each position+ of the table publish's answer on the plain and the managed route, and fails if it+ reaches a halt, the console, a verify detail, the listing's output, `build-log.jsonl` or `build-status.json`, the+ caption's own places aside.+- **Verify** (`verifyCommandStates`, `verify-spec.js` kind `command-state`): each declared entry's exact row stores+ each declared flag — stored state only, not what the app renders. A reader without command-row access, or a+ failed read, fails every entry. A verify of a run that did not run the `commands` phase (exactly `--stage data`)+ reports each entry as `phaseSkipped` (`command-state:<table> <bar> row <rowId>`) and reads no row; a verify with+ no phase list is unrestricted and stays fail-closed.+- **Changed-only**: the `commands` slice includes `commandStates` (by row id) only when some are declared; any change+ is a full build with no debt (`classify-changes.js`), and a spec that declares them never takes a no-op or fast+ apply (`COMMAND_STATES_FULL`, `changed-only-flow.js`).+- **Teardown and download** do not read or restore command states: teardown validates them under the structural+ profile (findings are warnings), and download never writes `commandStates`.+## Local DevelopmentTest this plugin locally:@@ -3651,6 +3788,7 @@ scripts/list-languages.js ← /genpage planner: the environment's base language and each provisioned language (LCID, culture code, right-to-left) — the SDK's `getEnvironmentLanguages()` over the az-token client, three reads and no write, printed as one pure-ASCII JSON line. The only source: no `pac model list-languages` stands behind it, because every /genpage page operation needs the Azure CLIapps.js ← the replacement for `pac model list` and `pac model create` that /genpage and /app-builder run (`pac-replaced-docs.test.js` pins that their text names this script, not the `pac` commands): the environment's model-driven apps and a new app that opens on generative pages, through the bundled SDK. `list` prints each app's id, name, unique name, description and two facts, apart: `published` (it has a row in the published layer: users can open it) and `unpublishedChanges` (it has a saved row that is not published) — drafts included; `pac`'s "(Saved - Not Published)" is neither of them (see the spec section) and never part of the name. `create --name --solution --page-id <guid> [--page-id …] [--unique-name] [--description] [--publish]` makes the app with one area "Main", one group "Pages" and a sub-area per page, titled with the page's stored name; the app, its sitemap and its pages join the solution (`inSolution`: `app`, `sitemap`, `pages`; the add of an app brings its sitemap but never the pages its navigation opens, so each page is added on its own as the page table's component type, read from the environment before the first write — `lib/page-solution.js`, AB#6443257; a system solution such as `Default` holds them already: `systemSolution: true`, and nothing is read for it); it is published only with `--publish`. The default public view of each table the pages read (the tables come from each page's own configuration, the views from the page backend: the definition `placeInApp` pins with) joins the app's components in the create itself — `components.views` of the app the SDK creates, written by the same AddAppComponents that adds the sitemap — as `pac model genpage upload --app-id` pinned them; the output says what was pinned (`dataSources`, `pinnedViews`), a table with no default public view or a page held as raw files is named in `warnings`, and a page that cannot be read refuses the create before the first write. Every check — no page id, a page that does not exist, a solution that does not exist or is managed, a taken unique name, an unreadable base language — is a refusal printed as `{ ok: false, code, error, written: false }` before the first write; a failure after the push began reads the platform back and prints what is actually left of this create (its rows are recognised by their ids, and a row that holds the unique name under another id is named apart)list-tables.js ← the replacement for `pac model list-tables` (the skills' and agents' text runs this script: `pac-replaced-docs.test.js`): the environment's tables — the SDK's `findTables(term)` for each comma-separated `--search` term, a few reads at a time, joined without repeats; `--exact` keeps the tables whose logical name IS a term and names the terms no table has (`missing`), from one read of every table; `--type custom|standard|all` is `pac`'s own filter, `custom` through the SDK's `customOnly` option. One pure-ASCII JSON line of `{ logicalName, displayName, schemaName, isCustom }` rows. An answer that is no list of tables — a 2xx with no `value` list: a sign-in page, `{}`, `null` — fails `TABLES_UNREADABLE` (exit 1) instead of reading as "no tables, every searched one missing" (`lib/collection-answers.js`)+ list-command-states.js ← read-only: the modern command buttons (`appaction` rows) of an app's tables — `--env --app <uniqueName> [--entity <logical>] [--location MainTab|HomeTab|ContextualTab]`. Each button with its row id, bar (a stored location the App Spec has no name for is `unsupported`, never mapped onto one), scope (`table`, `app`, `other-app`), stored `hidden` / `disabled`, and `candidate` with every reason it is not one, in the fixed vocabulary of `lib/command-state-contract.js` (`REASONS`). Only table-scoped rows are candidates: an app-scoped row, this app's own included, is `app-scoped` (`command-state-app-scope-unverified`); a present null `visibilitytype` with every visibility-formula column empty is static (what a `commands[]` build stores), a missing column is unreadable. Excluded rows (inactive, managed, migrated, nested, containers, app-scoped) are listed with their reasons, never left out; two buttons with one caption on one bar each name the other in `sameCaption`. It reads the app by unique name (exactly one), its current layer and complete table list, whether `appaction` keeps row versions (`IsOptimisticConcurrencyEnabled`; off: no candidate), and every page of each table's commands by `contextvalue`, through `lib/command-state-read.js` and the GET-only allowlisted transport `lib/command-state-transport.js` (the SDK's API root, the raw az-token client, each answer read whole). A write flag (`--apply`, `--publish`, `--authorize`, `--yes`, `--force`) is a usage error. A failed or incomplete read is `{ ok: false, code: "command-state-…", error }` and exit 1, never a shorter list. A candidate is a row whose shape allows a row-state edit; the listing proves nothing about how the app renders it (`command-state-read.test.js`, `list-command-states.test.js`)get-lookup-metadata.js ← /genpage planner: the lookups of the tables a page reads — each column's read property, its COMPLETE target set (the SDK's `fetchEntityMetadata`) and the concrete per-target paths a filter may go through (navigation property and target key, from `readRelationshipsOf`'s lookup-details mode), shared paths such as Owner's `ownerid` kept apart and never a target discriminator (`lib/lookup-metadata.js`). One pure-ASCII JSON line only after every read completed; a missing table, a lookup without targets or a failed or malformed relationship page is `{ ok: false, code, error }` and exit 1, never a shorter candidate list. The planner saves it as `lookup-metadata.json`add-page-to-solution.js ← Adds GenPages and optional connection references to a solution (Phase 6.7 packaging); the app id is optional, so it also adds pages alone — the recovery `genpage-upload.js --solution` names when a page's own add failed (a page is a component of its own: the app is not one of its required components)solution-settings.js ← Deployment settings: `template` writes the settings file of a solution or a package (pac's own format), `import` imports a package and applies the settings in the same import — the SDK first, `pac solution create-settings` / `import --settings-file` only where it refuses (pac is given a private copy of the settings the run read, owner-only on every platform and removed however the process ends, never the file's path); ExportSolution, StageSolution and ImportSolution are each sent exactly once — but for an ImportSolution the platform refused to start because another operation held its customization lock (HTTP 429 with one of the customization-lock error codes whose documented text is "Cannot start …", or with `0x80071151` and "Cannot start …" words), which is sent again under a new job id once the refused send's job proves that nothing of the package was applied — `importjobs(<id>)` does not exist (404) or, for `0x80071151`, read once at once, is a finished job whose log says the import failed with that error before it processed the solution or any component (`lib/import-job-proof.js`); a job that proves nothing ends the retry with a sentence that says why and what to do, and so does a fifth `0x80071151` refusal, whose job is not read (at most five sends and five minutes in all — asked again after every wait — a `Retry-After` waited whole or the retry ended; `importAttempts` / `importRefusals` in the output) — every text it prints has the settings file's values taken out, and everything it prints or writes the access tokens the run sent (an HTTP 200 can be a failed staging whose message quotes what it was given), and a failed import names its job and the job log's reason; one pure-ASCII JSON line with `source`@@ -3704,6 +3842,10 @@ scripts/dataverse-operations.js ← The reviewed built-in operation catalogue (frozen, revision 1): exact-name lookup, the four-key actionBindings projection (toActionBinding) and the new-row check; no I/O, not gatedsdk-build.js ← app-builder build engine (idempotent; incl. the pages phase). Every way it pushes or publishes the app is one of `appWriters`, which first awaits `publishTablesBeforeApp` (the one request that publishes, before the app, the tables whose forms or charts its publish ships)app-components.js ← shared current/published app layers (`currentLayerRows`, and `currentLayerRow` — the authored layer wins — for a listing), component inventory (`readAppComponentInventory`: the download's read, with two opt-ins the build's pre-app proof makes — `savedLayer`, which looks the tables of the form and chart components up in the SAVED layer, and `requireIdentified`, which reads the answer strictly: a row counts for an id the list asked about, two tables for one id or a value no table has make the read incomplete, and a row of the component list that cannot be placed — no record, no GUID objectid, another component type — makes the list unreadable), hidden-table pin/proof, Main-form resolution/membership and push directives, `collectionRows`, the one reader of a paged collection, and `savedPageRows`, the one reader of the generative-page rows in the SAVED layer (RetrieveUnpublishedMultiple, 50 ids a read): a plain read of the page table answers the published layer only, so a page that was created and never published is "not found" by it — `apps.js` and teardown read pages here+ command-state-contract.js ← the vocabulary of a modern command's row state, shared by its readers: the bars (`LOCATION_BY_BAR`; any other stored location is `unsupported`), the columns a row is read with (`ROW_SELECT`), the fixed reasons a row is not a candidate (`REASONS`) and the refusal code each stands for (`codeForReasons`), `canonicalRowId`, `CommandStateError`; and the App Spec's `commandStates[]` (2.24.0): `validateCommandStates` (closed fields, table scope only — `scope: "app"` is `command-state-app-scope-unverified` — and the `minimumPluginVersion` floor), `normalizeCommandStates` (desired flags by column name, `hidden` / `isdisabled`), `diffCommandFlags`, the two exact approval tokens (`commandStateApprovalKey`: one row version under one intent in one environment; `commandTablePublishApprovalKey`: one table) and `commandStateAuthorizationKeys`, which claims both families out of `--authorize` and refuses a malformed or undeclared one+ command-state-transport.js ← `createCommandStateTransport({ client, apiUrl })`: the reader `list-command-states.js` and the build read through — the raw az-token client under the SDK's API root, limited to the app, layer, component, table-definition and `appactions` paths the feature reads (`READ_PATHS`); a continuation is read only on that origin and root. Its one write, `patchRow` (only on a client with `patch`: the build's own), is a conditional flag-only PATCH of one `appactions` row (`If-Match` the read version, a body of `hidden` / `isdisabled` only). It is the feature's raw-request exception to "every write goes through the SDK": the SDK has no update of an `appaction` row's flags. That client is made only for a spec that declares `commandStates` (`build-model-app.js` `makeSdk`), behind the same publication barrier and write gate, and sends its PATCH once whatever answers it (`commandStateSendOnce`)+ command-state-read.js ← `resolveCommandStateContext` (one app by unique name, its current layer and complete table list, `appaction`'s `IsOptimisticConcurrencyEnabled`), `readCommandStateRow` (one row by id; only a 404 with `0x80040217` is "no row"), `decodeCommandStateRow` (strict: a missing column is not a null, a null flag is not `false`, a number spelled as text is unreadable; every reason, never the first only) and `listCommandStateRows` (every page of each table's commands by `contextvalue`; a repeated row id or a row that is no record fails the read; `sameCaption`; a fixed order). Static visibility is a PRESENT `visibilitytype` of null or 0 with every visibility-formula column present and empty — the null the platform stores on a button `commands[]` wrote is static; nothing ever writes `visibilitytype`. Only a table-scoped row is a candidate (`app-scoped` otherwise). `verifyCommandStates` is `--verify`'s check of each declared entry: its exact row, on the declared table and bar, stores each declared flag (stored flags only, never how the button renders; a read that fails fails the entry)+ command-state-run.js ← the build's `commandStates` writer. `commandStateMode` (off / plan for a dry run / data-stage / apply = a full build with `--publish`; anything else is refused before a read), `createCommandStateRun` (per attempt: the earliest preflight reads the app context and every declared row and checks the exact approvals before the build's first write; the commands phase re-reads each row and sends one conditional flag-only PATCH per changed row, never resent — a 412 is `command-state-version-conflict`, a lost answer `command-state-write-unknown`; a refusal or unknown outcome is a `BuildHalt` with `retry: never`) and `createCommandStatePublicationObserver` (one per invocation: records whether the existing before-app table publication — plain, or the managed publisher's flush — named each declared table after its latest row write; an apply succeeds only when every declared table is confirmed, else `command-state-publish-unconfirmed`; it adds no store and no cross-run fence)app-pin-recovery.js ← settles an app push whose component pin answered `APP_PIN_OUTCOME_UNKNOWN` (`pinIntentOf`, `pinWarningOf`, `reconcileUnconfirmedPin`): confirm from a read, repair with one more push of the same writer, or report it unconfirmed; never a second repairapp-publication-policy.js ← the build's app-publication port (`createAppPublication`): a pass-through of `appWriters.publish` until an exact Main-form list owes a publication; then a guarded publish, settled only by a read of the published layer, and `flush()` / `unsettled()` for what is still owedsolution-membership.js ← one read of a solution's components (the types the build adds, plus its tables: a table held with all its subcomponents vouches for its views, forms and charts, which have no rows of their own), so a rebuild adds just what the solution is not PROVEN to hold; every doubt reads as "add"@@ -3771,6 +3913,7 @@ scripts/app-component-scope.js ← what an edit of an app that is not about its components may ADD to them, held at the SDK's transport (`makeAppComponentScope()`: `wrap(httpClient)`, `limit(appId, { views }, work)`). Every `pushArtifact('app', …)` of an existing app (the bundle's `appApi.update`) PATCHes the sitemap and then posts ONE AddAppComponents whose list it DERIVES: for each Entity sub-area the table, EVERY active Main form, EVERY active public view and EVERY chart, for each DashBoard sub-area the dashboard — whether or not the app has them, and `components.mainFormsByTable` narrows the Main forms alone. AddAppComponents only adds, so a page edit that went through it put back what the app's maker had taken out, and its publish made it live. The bundle is never patched and cannot be told to skip the derivation, so the page backend (`placeInApp`, `removeFromApp`) keeps the SDK's sitemap write and has the post limited where it leaves the process: to the views the edit pins, and — when none is left — not sent at all (the SDK is answered with the service's 204). The action is found by the PATH of the address, percent-decoded as a whole before its trailing slashes are dropped and its last segment is read (a query string or fragment that mentions the name is not it; `AddAppComponents%2F` and `%41ddAppComponents` are it, in another spelling), and every POST is read ONCE while an edit is open — its address as text, its body as the plugin's transport takes it (text as it is, bytes copied, an object serialized as the transport serializes it and read back as plain data) — decided on in that CANONICAL form and sent in that form in every branch (the action it cuts, another app's request, a request to another address, a batch), never the object, bytes or address the caller holds, which the transport would read again: a `toJSON`, a getter or an address that answers differently the second time cannot undo the limit, and JSON text and the UTF-8 bytes of it are parsed for the action. While an edit is open, a request that IS the action in a shape the limit does not read — another spelling of the name, an address or path that cannot be decoded, a body that is JSON text (for a `post`), is not JSON or cannot be serialized, or has no list — or that does not carry every view the edit pins (a view named as a reference, or left out), or a `$batch` that may carry the action, through `post` and `postRaw` alike (a part of a batch cannot be limited: one classifier reads a multipart batch request line by line and a JSON batch entry by entry, each address as any address is read, and a JSON batch after its JSON is), is REFUSED with the bundle's `SdkError` `APP_COMPONENTS_NOT_LIMITED`: not sent whole and not answered as done. The one change set read whole is the bundle's guarded pin (since model-apps 2.20.6: an unpublished default-mode push that holds the app token and reads a derived component missing from the current layer sends `PATCH {}` under that token, the action and an echoed `PATCH {}` as ONE change set): for an app with an edit open, exactly that change set is not sent, and the SDK is answered with a refused guard, so it sends its plain action once, limited as above — no app-row write, the writes of earlier releases; any other change set that names the action is refused. The bundle of 2.21.0 says so in a note of the push, `APP_PIN_TOKEN_UNCONFIRMED (guardRefused)` (the app token it holds may be stale): `limit` takes out that one note for that app when the limit itself answered the guard — nothing reached the service, and the page backend fetches the app with overwrite before each push it makes, so no edit is made under that token — and keeps every other (`APP_PIN_REBASE_REQUIRED`, a guard the service refused). `placeInApp` reports in `pinnedViews` only the views the app's current layer is read back holding after the push, and warns of the rest. A raw POST (`postRaw`: a real POST whose body the transport does not touch, which the bundle uses for `$batch` only) is told by its address exactly as a `post` is, so the action cannot escape the limit by the method that carries it: one to the action's address is limited as the object form is when its body is JSON text of the same object, the UTF-8 bytes of it or an object, and what goes on is a form the transport sends as it is — JSON text for text and for bytes (the transport would send a Buffer as `{"type":"Buffer",…}`), the plain object for an object — with any `Content-Length` the caller declared, in whatever spelling, rewritten to one header with the exact length of what is written; it is refused when its body cannot be read that way. The SDK reports that as a warning of the push ("one or more components were not pinned"), so the sitemap the edit saved stays saved and nothing unlimited reaches the app. A page is a GenPage sub-area, which needs nothing from the app's components, and everything the SDK derives belongs to a sub-area that was there before the edit. The build owns the whole app and never opens an edit; an SDK lent to the backend keeps its owner's transport, and is not limited. Pinned against the real bundle by `genpage-app-edit-real-bundle.test.js` — the re-vendor tripwire for the request's shape, which also pushes the app through the limit — over the plugin's own transport, under a fake service that reads the wire (the body as JSON, a `Content-Length` that must be its length) — with that request changed, or sent through the raw method, to see the limit and the refusal as the user doesgenpage-base.js ← base-marker hash, compare, and read/write (sibling dotfile of the code file; no environment URL; `appId` is optional — a page created before any app held it is recorded with the page alone, and the first update that names the app it was then placed in goes ahead on that marker and records the app; `unfinished` (`publish` or `place`) is set only by an upload that CREATED the page and did not finish it, and is what lets `genpage-upload.js --page-id` finish exactly that page — it is cleared when the page is finished, and `genpage-base.js record` never writes it)safe-fs.js ← confined output writes and deletes: the named directory's final component must not be a link or junction (readlink, not a path-text compare, so an 8.3 name and a share root stay usable); write via exclusive temp + rename, or — with `exclusive: true` — never replace a name: the content goes to a sibling file this process created exclusively and is published with a hard link to the target name (which fails if the name exists, so the file system decides and a file that appeared meanwhile is never overwritten: `IO_ERROR` with `reason: 'exists'`; where hard links do not exist the write fails closed, `reason: 'no-hard-links'`), and only that sibling is ever removed — retried, and reported (a warning after a publish, the error after a failure) when it cannot be — and a later write of a file that still has its second name is refused naming it. Everything it writes or appends has the access tokens the process obtained taken out first (`lib/output-redaction.js` `redactFileData`: a text as a text; bytes — any ArrayBuffer view, or a string given with a `hex`, `base64` or `base64url` encoding — masked with as many `*`, and data it cannot read refused before anything is written): it is the one writer of the build's journal and status file, of a download's files and of a page's file and its deployed copy. Shared by genpage markers and later callers+ rename-retry.js ← the one rename that outlasts a brief Windows file lock (EPERM, EACCES or EBUSY while a scanner or a second process holds the file): on win32 only, the same rename is repeated after growing pauses (25 ms doubling to 1 s), at most 5 s for one rename and 30 s for the whole process (the wait blocks the event loop, so it must stay well inside the teardown heartbeat and the transport's timeouts; once the 30 s are spent every later refused rename is ONE attempt), then the ORIGINAL error is thrown untouched, so every caller keeps its message and code; any other platform or code is one attempt. Used ONLY by `apply-snapshot-store.js` for files the plugin owns: those it serialises with a lease and compare-and-set (`writeFileAtomic` — which the managed binding store, the snapshot and the page, dashboard and web-resource records write through) and the distrust markers, which take no lease (they must be recordable while another writer holds it) but are each created under a name unique to the call; each site has a note why repeating is safe there; a target that an unleased writer can also write passes `{ retryLock: false }` and renames once (the deployed baseline, which the download writes without the build lease). NOT used by `safe-fs.js` (a maker's files and the diagnostic status file keep their own 25-400 ms waits), by the folder move-aside of `clearWorkspace` (one attempt: the approval was for the folder as it is now) or by `temp-workspace.js` (its own shorter waits). A test that keeps a rename failing for good calls `tests/helpers/short-rename-wait.js`, which also restores the process totalhydrate-spec.js ← reconstruct an App Spec from a deployed app (edit flow)verify-spec.js ← spec-vs-deployed reconciliation core (checks are ordered tasks on a pool of 4)status-reasons-keys.js ← a table's status reasons (with their states) and alternate keys (with their columns), one narrow read each (`readStatusReasons`, `readAlternateKeys`: `{ state: 'ok' | 'absent' | 'error' }`, never a throw), and the checks of the declared ones against them (`statusReasonChecks`, held to the build's own `statusReasonTargets`; `alternateKeyChecks`) — verify's `status-reason` and `alternate-key` checksdiff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex 57aa0fda5..faa6162d8 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -5,6 +5,20 @@ 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.24.0]++- **Command buttons, read-only:** `scripts/list-command-states.js` lists an app's modern command buttons by row id: each button's bar, scope, stored hidden and disabled flags, and the reasons a button is not a candidate. Nothing is written (#812).+- **Show or hide existing buttons:** on a full build with `--publish`, `commandStates[]` (with `minimumPluginVersion: "2.24.0"`) sets the hidden and disabled flags of an existing table-scoped modern button, by row id, with one conditional write; a dry run prints the exact approvals needed (#812).+- **Publication:** publishing a table publishes all saved customizations on it, for every app that shows it, so it has its own approval. Until that publication is confirmed, the build reports `command-state-publish-unconfirmed` and what each row is known to hold.+- **Windows:** a brief file lock (antivirus, indexer) on the binding store, the changed-only snapshot, or page and recovery records no longer stops a build: the rename is retried up to 5 seconds, 30 in all per process, then the original error is reported (#830).+- **Verify:** a protected duplicate rule is judged as the build judges it, so swapped condition criteria, a renamed condition key or omitted `conditions` now fail with `DRIFT`, naming the conditions, instead of passing a rule the build refuses (#831).++### Limits++- Only table-scoped modern buttons with static visibility can be changed; app-scoped and Power Fx buttons are refused, and classic out-of-box buttons are out of reach. Removing an entry or a teardown restores no flag, and download does not write `commandStates` back (#812 stays open).+- A table publication that was sent can still complete after a halt, or after you remove the entry; this release keeps no record of it across runs.+- A modern button set to `disabled` is not shown at all, rather than greyed out.+## [2.23.0]- **Configuration identities (opt-in):** with `configurationIdentity: "stable-v1"`, environment variables, connection references, Custom APIs and duplicate-detection rules, with their children, are created at reserved ids and bound; a create whose answer was lost is never sent again (#807).diff --git a/plugins/model-apps/docs/app-builder-capabilities.md b/plugins/model-apps/docs/app-builder-capabilities.mdindex dcfa8c857..19356dfb3 100644--- a/plugins/model-apps/docs/app-builder-capabilities.md+++ b/plugins/model-apps/docs/app-builder-capabilities.md@@ -167,6 +167,26 @@ apart deliberately.- Modern command-bar buttons — functional **JS on-click** + static hidden/disabled, incl. **flyout / split-button menus**.- Web resources (JS / HTML / CSS) shipped + added to the solution; idempotent (reuse by name). One whose publication the SDK could not confirm (`WEB_RESOURCE_UNVERIFIED` — its publish refused under the customization lock, say) is still added to the solution, recorded in the build workspace, and written again by id on the next run, never created twice (`lib/web-resource-records.js`; `web-resource-unconfirmed.test.js`).+### Existing command button state (`commandStates[]`) — ✅ verified live (grid and form bars)+- `list-command-states.js` (read-only) lists the modern command buttons of an app's tables by row id, with+ their bar, scope, stored `hidden` / `disabled` and whether each is a candidate (and the reasons it is not,+ from the row's shape).+- `commandStates[]` (`minimumPluginVersion: "2.24.0"`) sets the stored `hidden` / `disabled` flags of an+ existing **table-scoped** button, picked by that row id, with one conditional flag-only update per changed+ row — only in a full build with `--publish`, and only with the exact approvals a dry run prints (one per row+ version and intent, one per table to publish). App-scoped buttons, other button properties and creating a+ button are out of scope; keyed `commands[]` cannot be combined with it.+- Measured against the platform API: a row read straight after the update returns the saved flags and a new+ row version before any publish; a stale version is refused (412) and the newer content kept; the table+ publication the build already makes answers success. `--verify` checks those stored flags only.+- **Verified live in a browser:** after the build's own approved update and table publication, the served+ grid and form command bars of two apps sharing the table hid and showed the button as declared, for a plain+ and a managed-routed table, and a button set to `disabled` was not shown at all. A saved change reached a+ fresh browser session at once; a session with cached data kept the old bar until it reloaded its data.+- **Not verified in a browser:** the sub-grid (`ContextualTab`) bar, checked through the API only. `--verify`+ checks the stored flags, not what a browser paints.+- Tests: `scripts/tests/command-state-*.test.js`, `list-command-states.test.js`.+### App theme and header logo (Preview) — 🧪 tested- `app.theme` sets the app's **modern theme** — a base palette colour (or explicit palette slots), headercolours, an optional font — and a **header logo** (an existing image web resource and its tooltip).diff --git a/plugins/model-apps/docs/app-builder-design.md b/plugins/model-apps/docs/app-builder-design.mdindex 6ece8c956..40f86a88f 100644--- a/plugins/model-apps/docs/app-builder-design.md+++ b/plugins/model-apps/docs/app-builder-design.md@@ -624,6 +624,11 @@ full build / HALT.4. **app-shell sitemap** — structural sitemap change only (app.description/icon excluded).Additions of NEW top-level artifacts, removals, and charts/commands/dashboards/web-resource-content/AI ⇒full build, and they incur sticky **debt**.+A spec that declares `commandStates[]` (2.24.0) is never fast-applied and never a no-op: a full build reads+every declared command row and asks for approval of what it finds, which an unchanged snapshot cannot stand+in for (`COMMAND_STATES_FULL`, `lib/changed-only-flow.js`). A change to them (added, changed or no longer+declared, matched by row id) is a full-build reason with **no** debt: the full build applies it, and an entry+no longer declared leaves its row as it is, which no later build could close either.## Snapshot envelope (`<workspace>/apply-snapshot.json`, schema 3, atomic)`{ schema, orgId (live WhoAmI), envUrl, appUniqueName, appId, solutionUniqueName, generation (uuid),diff --git a/plugins/model-apps/docs/architecture.md b/plugins/model-apps/docs/architecture.mdindex 3d4e9f50d..336943111 100644--- a/plugins/model-apps/docs/architecture.md+++ b/plugins/model-apps/docs/architecture.md@@ -225,6 +225,14 @@ deterministic, idempotent, narrated SDK build. Create and **edit share one path*`--non-interactive`/autopilot mode suppresses prompts only — it never bypasses safety gates.The durable `<app>_pagemanifest` web resource carries page semantics across download and rebuild.+**Existing button state (`commandStates[]`, run 2 only):** a full build with `--publish` reads every+declared command row and checks its exact approvals in the earliest preflight, before the first write;+the `commands` phase re-reads each row and sends one conditional flag-only update per changed row+(`lib/command-state-run.js`); the existing before-app table publication (`publishTablesBeforeApp`)+also names each declared table, and the run succeeds only when that publication is seen to cover the+latest row write. No SDK push and no publish request of its own is added. Exactly `--stage data` leaves+command states alone; any other partial apply is refused before it reads.+**One apply at a time (build lease):** each `--apply` run — the data pre-build (run 1), the full build(run 2) and a `--changed-only` apply — holds the app's build lease in its workspace(`<workspace>/app-build.<hash>.lock`, `lib/app-operation-lease.js`) from before its auth check to itsdiff --git a/plugins/model-apps/references/app-spec-schema-advanced.md b/plugins/model-apps/references/app-spec-schema-advanced.mdindex 066a3debc..d6c05bf47 100644--- a/plugins/model-apps/references/app-spec-schema-advanced.md+++ b/plugins/model-apps/references/app-spec-schema-advanced.md@@ -114,11 +114,13 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the ctakes no arguments. **Without a parameter the function is invoked with no arguments**, so`primaryControl` is `undefined` and the button appears to do nothing — the error is visible onlyin the browser console, and the build, the deployed rows and `--verify` all still look correct.-- **Button edits are not applied on rebuild.** The command phase is discover-then-skip: it creates a- bar only when none exists. To change a deployed button, delete the entity's commands (or tear down)- and rebuild.+- **Button edits in `commands[]` are not applied on rebuild.** The command phase is discover-then-skip: it creates a+ bar only when none exists. To change a deployed button's label, script or other properties, delete the entity's commands (or tear down)+ and rebuild. To only show, hide, enable or disable an existing button, use `commandStates[]` (below).- **`location`** is `MainTab` (default — the entity form/grid command bar), `HomeTab`, or `ContextualTab`.-- **`hidden`** / **`disabled`** set *static* visibility/enablement. **Conditional (rule-based)+- **`hidden`** / **`disabled`** set *static* visibility/enablement. A modern button with `disabled: true`+ is not shown at all (live checks found it absent from the bar, not greyed out), so `disabled` acts like+ `hidden`. **Conditional (rule-based)visibility is not supported** — it's Power Fx-only on modern commands and needs a component librarythat can't be authored headlessly.- **`type`** is `Button` (default), `FlyoutAnchor`, or `SplitButton`. A flyout/split container holds@@ -127,6 +129,106 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the csupported (it needs a parent command-bar row the SDK doesn't synthesize from scratch). The commandlands in the Default solution but is entity-scoped, so it shows on the entity's command bar.+### Listing the existing buttons — `list-command-states.js` (read-only)+```bash+node scripts/list-command-states.js --env <envUrl> --app <uniqueName> [--entity <logical>] [--location MainTab|HomeTab|ContextualTab]+```+Prints every modern command button of the app's tables (or of the one `--entity`), each with its+`rowId`, `bar`, `scope` (`table`, `app`, `other-app`), stored `hidden` / `disabled`, and `candidate`.+It only reads; a write flag is a usage error.+- **Pick a button by `rowId`, never by caption.** Two buttons with the same caption on one bar each+ name the other in `sameCaption`; an unlabelled button has `caption: null`.+- **Excluded buttons are listed, not left out**, each with every reason it is not a candidate:+ `shape-unreadable`, `id-mismatch`, `context-not-table`, `context-mismatch`, `table-not-in-app`,+ `location-unsupported`, `location-mismatch`, `app-scoped` (scoped to an app — this one or another — not to its table: only+ table-scoped buttons are candidates in this version), `not-standard-button`+ (a flyout or split container, or a group), `nested` (a menu item), `not-default-origin` (migrated+ or system), `inactive`, `managed`, `not-customizable`, `flags-unreadable`, `visibility-formula`+ (Power Fx visibility or classic rules: `visibilitytype` other than empty or 0, or a visibility-formula field set; the+ empty `visibilitytype` the platform stores on a button `commands[]` wrote is static), `formula-action` (a Power Fx on-select), `version-unavailable` (the+ platform keeps no row versions for commands). The listing does not check each row's own version; the+ build does, and refuses a row without one (`command-state-version-unavailable`).+- A bar the App Spec has no name for (a stored location other than 0, 1, 2) is `bar: "unsupported"`.+- **`candidate` describes the row's shape only.** It does not prove the app renders the button, or+ where.+- A failed or incomplete read prints `{ "ok": false, "code": "command-state-…", "error" }` with+ exit 1 — never a shorter list.++## commandStates[] (optional — show or hide existing buttons)+```jsonc+"minimumPluginVersion": "2.24.0", // required: an older plugin refuses the spec instead of ignoring it+"app": { "uniqueName": "new_support", ... }, // required: the app the buttons are checked against+"commandStates": [+ { "entity": "new_ticket", "location": "MainTab", "scope": "table",+ "rowId": "11111111-1111-4111-8111-111111111111", // from list-command-states.js — never invented+ "hidden": true }, // and/or "disabled": true|false+ { "entity": "new_ticket", "location": "HomeTab", "scope": "table",+ "rowId": "22222222-2222-4222-8222-222222222222", "hidden": false, "disabled": false }+]+```+Sets the stored **hidden** and **disabled** flags of a modern command button that already exists,+picked by its row id. Nothing else about the button changes, and a row is never created.+- **Fields are closed and exact.** `entity` is a table declared in `entities[]`; `location` is exactly+ `MainTab`, `HomeTab` or `ContextualTab` and must be the row's bar; `scope` is exactly `"table"`;+ `rowId` is the lower- or upper-case id `list-command-states.js` prints (no braces, not all zeros), one+ entry per row; set `hidden`, `disabled` or both. A flag you leave out is never changed or compared+ with a wanted value, but both stored flags must read as `true` or `false`: a row whose other flag+ cannot be read is refused before anything is written (`command-state-row-unreadable`);+ `false` is an instruction, not "unset". An unknown field (for example `isdisabled`) is refused with+ `command-state-spec-invalid`.+- **Table-scoped buttons only.** `scope: "app"` is refused with `command-state-app-scope-unverified`,+ and so is a row that turns out to be scoped to an app.+- **Only candidates are written:** an active, unmanaged, customizable, top-level plain button with no+ Power Fx visibility or on-select formula, on the declared table and bar, that the platform keeps row+ versions for — the listing's `candidate: true`. A button with an empty (null) `visibilitytype` and+ every visibility-formula field empty — what `commands[]` writes — counts as static; the build never+ writes `visibilitytype`.+- **Only a full build with `--publish` applies them.** A partial range, a changed-only fast apply or an+ apply without `--publish` is refused before anything is read (`command-state-phase-unsupported`,+ `command-state-publish-required`); exactly `--stage data` leaves them alone. A spec that also has+ keyed `commands[]` (`key`) is refused (`command-state-keyed-unsupported`), and so is `commands[]` that+ would create a new bar on a table whose existing button `commandStates` edits+ (`command-state-legacy-create-conflict`): create the button in one build, add its state in a later one.+- **Exact approvals, printed by a dry run.** A dry run reads each row and prints, for every row that+ needs a change, `--authorize overwrite:command-state:<table>/<bar>/<rowId>/<sha256>` — one version of+ one row under one intent in one environment — and for every declared table+ `--authorize publish:command-state-table:<table>/<sha256>`. An apply without every one of them+ writes nothing (`command-state-approval-required`, `command-state-publication-approval-required`);+ a row changed after its dry run needs a new token (`command-state-approval-stale`). There is no+ wildcard and no blanket approval. Such a halt prints the tokens it needs on the console, never into+ the build's log or status files.+- **Publishing a table publishes ALL saved customizations on it** (anyone's, not only these buttons),+ for every app that shows the table — which is why it has its own approval.+- **One conditional write per row.** The build sends only the flags that differ, with `If-Match` on+ the version it read. A row changed in between is refused (`command-state-version-conflict`) and never+ overwritten. A write whose answer was lost is never sent again (`command-state-write-unknown`): read+ the row with `list-command-states.js` before building again.+- **Success needs the table's publication.** The build publishes each declared table with the tables+ it publishes before the app; until that publication is seen to succeed after the row's write, the+ build reports `command-state-publish-unconfirmed`, saying for each table what its rows are known to+ hold ("saved, not published"; or, when that is all it knows, "held after a write with no usable answer",+ "held other flags than declared at its last read", "could not be read at its last read", "write outcome+ unknown" or "not written") —+ a saved row holds the flags, but the button may still show its old state. A row that held its flags+ after its write (or already held them) and then changed before the build finished its rows is reported+ as `drifted`, with what the build did to it first (`command-state-not-confirmed`).+- **What the bar shows.** Live checks found a saved flag change served to a fresh browser session at+ once; a session with cached data can keep showing the old bar until it reloads its data (refresh, or+ clear the site's stored data). A button set to `disabled: true` was not shown at all, as with `hidden`.+- **The end of the build checks again.** After its app work the build resolves the app afresh and reads+ every declared row once more: a table no longer in the app, or a row that no longer holds its flags,+ fails the build. Nothing is rolled back — the rows it wrote stay written, and the message says what this+ build did to each row (wrote it, found it already set, or sent a write that got no usable answer) and+ what each read found. When the build retries itself, a row an earlier attempt wrote is still reported+ as written by that attempt, and is never written again.+- **Delayed publication is not fenced.** A table publish that was sent can still complete after a+ halt, or after you remove the entry. This release keeps no record across runs: the next publishing+ run requests the table again only because `commandStates` still names it.+- **`--verify` checks stored flags** of each declared row — not how the button renders (a verify of+ `--stage data` lists them as phase-skipped and reads no row). A changed-only+ apply of a spec with `commandStates` always runs the full build. Removing an entry, or a teardown,+ does not restore a flag, and download does not write `commandStates` back into a spec.+## businessRules[] (optional — declarative form logic, no code)```jsonc@@ -1268,6 +1370,17 @@ the field builds exactly as before.`configuration-row-not-found` even when a namesake exists, an item with no binding (or no readablebinding store) fails with `create-identity-unverified`, and an item whose create is still beingsettled is reported unverified. Keep the build workspace with the binding store where verify runs.+ A protected duplicate rule's conditions are checked at their bound ids too, as the build pairs them:+ criteria swapped between two bound condition rows fails with `DRIFT`, naming the conditions+ (`/conditions/<key>`), as the build refuses that rule (`configuration-edit-unsupported`). Verify+ judges that rule with the build's own read-only check, so an edit the build refuses fails with+ `DRIFT`, naming what it can: a condition added, removed or renamed in the declaration, a condition+ row the declaration does not name, `conditions` omitted while the rule's binding holds conditions, or+ a changed root field (for example `/matchingEntity`). `/definition` appears alone when the build+ refuses and no declared field says why (for example the rule's publication state changed). A bound+ row that is gone stays `configuration-row-not-found`, a binding read that could not be completed stays+ `create-identity-unverified`, and a rule whose content could not be read whole keeps its own read+ error (for example `DUPLICATE_RULE_READ_INCOMPLETE`): no edit can be judged from any of them.- **Checked before anything is sent.** Every declared protected item is read and judged before thebuild's first service change, the solution version included: a first create's reserved id and itsnamesake lookup too, so a create that would stop with `create-identity-conflict` ordiff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.mdindex d52902b9b..edda843ea 100644--- a/plugins/model-apps/references/app-spec-schema.md+++ b/plugins/model-apps/references/app-spec-schema.md@@ -35,6 +35,7 @@ to read the SDK, the lint, or the engine to author a spec. Common asks → how t| A related record's card shown on a form | `forms[].quickViews[]` (lookup + a `QuickView` form by name) | forms || A command-bar button that runs JS | `commands[]` (`library` + `function`; optional `hidden`/`disabled`) | commands || A command **drop-down menu** of buttons | `commands[].type: "FlyoutAnchor"` + `children[]` | commands |+| Show, hide, enable or disable an **existing** modern button | `commandStates[]` by `rowId` (from `list-command-states.js`; table scope only; needs `--publish` and exact approvals; [advanced](app-spec-schema-advanced.md#commandstates-optional--show-or-hide-existing-buttons)) | commandStates || A dashboard of chart/list tiles | `dashboards[]` (`tiles[]` reference declared `views`/`charts`) | dashboards || A dashboard in the app nav | a `dashboard` sitemap subarea in `appShell` (auto-pins it) | appShell || A table in the app but not its navigation | `app.tables` (logical names; additive membership) | app |@@ -832,6 +833,7 @@ list with "reach for it when…" guidance.| `globalChoices[]` | shared option sets || `webResources[]` | client-side logic || `commands[]` | modern command-bar buttons |+| `commandStates[]` | show, hide, enable or disable an existing table-scoped modern button by its row id || `businessRules[]` | declarative form logic, no code || `businessProcessFlows[]` | guided, staged process on a table || `dashboards[]` | chart/list/iframe/web-resource tiles |diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.jsindex 0e0a46765..908bfa1a2 100644--- a/plugins/model-apps/scripts/build-model-app.js+++ b/plugins/model-apps/scripts/build-model-app.js@@ -41,6 +41,9 @@ const { stagePhasesOrResolve, PHASES, STAGES } = require('./lib/stages.js');const { resolveAuthoringLanguage, BuildHalt, findExistingTable, entityHasLocalizedLabels } = require('./lib/entity-provision.js');const { createAzHttpClient, SQL_DEADLOCK_VICTIM } = require('./lib/sdk-http-client.js');const { createPublicationBarrier, describeWithheld } = require('./lib/publication-barrier.js');+const { usesCommandStates, commandStateAuthorizationKeys } = require('./lib/command-state-contract.js');+const { commandStateMode, createCommandStatePublicationObserver } = require('./lib/command-state-run.js');+const { commandStateSendOnce } = require('./lib/command-state-transport.js');const { RETRY, judgeFailure, retryPolicyFor, throttleAskOf } = require('./lib/retry-policy.js');const { makeThrottleBudget, waitDoesNotFit } = require('./lib/throttle-budget.js');const { workspaceBindingError, workspaceBindingNote } = require('./lib/workspace-binding.js');@@ -143,6 +146,13 @@ async function makeSdk(env, spec, workspaceDir, languageCode, { persistent = tru// variable value's create, a duplicate rule's publication) are screened as well. Inert outside a protected create set.const writeGate = managedCreateGate ? require('./lib/managed-create-transport.js').composeWriteGates(workflowEffectGate, managedCreateGate) : workflowEffectGate;const httpClient = createAzHttpClient(env, { throttle, sendOnce: (method, url) => isTranslationExport(method, url) || configurationSendOnce(method, url), ...(publicationBarrier ? { request: publicationBarrier.gateRequest(sendObserver ? sendObserver.wrap() : undefined) } : {}), ...(writeGate ? { workflowEffectGate: writeGate } : {}) });+ // commandStates (lib/command-state-run.js): a client of their own, made only for a spec that declares them, through which nothing but the+ // command-state transport sends (lib/command-state-transport.js: the appaction reads and one row PATCH). Its row PATCH is sent once, whatever+ // answers it (commandStateSendOnce): a conditional write sent again after an unseen answer would hide whether the first one landed. It is+ // screened by the same publication barrier and write gate as the client above.+ const commandStateClient = usesCommandStates(spec)+ ? createAzHttpClient(env, { throttle, sendOnce: commandStateSendOnce, ...(publicationBarrier ? { request: publicationBarrier.gateRequest(sendObserver ? sendObserver.wrap() : undefined) } : {}), ...(writeGate ? { workflowEffectGate: writeGate } : {}) })+ : undefined;const sdkTempDir = makeTempWorkspace('model-app-');const cleanup = () => {fs.rmSync(sdkTempDir, { recursive: true, force: true });@@ -242,9 +252,19 @@ async function makeSdk(env, spec, workspaceDir, languageCode, { persistent = tru// is the same client wrapped read-only, so it can be given out without the bypass above: a write through it is// refused before it is sent. Undefined otherwise, so a run without the flag gets nothing it did not get before.const previewHttpClient = previewPush ? require('./lib/readonly-operations.js').readOnlyHttpClient(httpClient).client : undefined;- return { sdk, provisionSdk, cleanup, isolatedReader, folderNote, previewHttpClient };+ return { sdk, provisionSdk, cleanup, isolatedReader, folderNote, previewHttpClient, commandStateClient };}+// The build's own `--verify` reader, from everything makeSdk returned (`made`): the same readers standalone verify gets (verify-model-app.js),+// so a check that needs one of them is never silently weaker inline. It takes the whole makeSdk result, not a hand-picked list, because a+// reader this call forgets fails every entry it checks: commandStates' rows are read with `commandStateClient`, and without it every declared+// entry failed inline verify after the build had applied it.+function inlineVerifyReader(made, spec, { genpage, workspaceDir }) {+ return readerFor(made.provisionSdk, appUniqueName(spec), {+ genpage, workspaceDir, isolatedReader: made.isolatedReader,+ ...(made.commandStateClient ? { commandStateClient: made.commandStateClient } : {}),+ });+}// Turn engine progress events into a phase-grouped, status-marked build log:// ▶ <phase>// [n/total] ✓ <label> (created)@@ -742,6 +762,18 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {return { ok: false, errors: [msg] };}}+ // commandStates (lib/command-state-run.js commandStateMode): an apply that cannot apply them — a partial range, no --publish, keyed+ // commands[] — is refused here, before anything is read. The engine refuses the same (sdk-build.js), for a caller that does not come this way.+ const commandStateModeOfRun = commandStateMode(spec, { apply: !!opts.apply, publish: !!opts.publish, phases: opts.phases || PHASES, changedOnlyFast: !!(opts.changedOnly && opts.changedOnly.fastApply) });+ if (commandStateModeOfRun.mode === 'error') {+ const msg = `${commandStateModeOfRun.code}: ${commandStateModeOfRun.message}`;+ log(`\n✗ ${msg}`);+ if (journal) journal.close({ status: 'halt', phase: 'preflight', label: 'command-state-mode', detail: commandStateModeOfRun.code });+ return { ok: false, errors: [msg] };+ }+ // One publication observer for the whole invocation, handed to every attempt: a table published by an earlier attempt stays confirmed until a+ // later attempt writes a row on it again.+ const commandStateObserver = commandStateModeOfRun.mode === 'apply' ? createCommandStatePublicationObserver() : null;// Pre-flight safety gate (apply only). Recomputed here — immediately before the write loop — so it// reflects live state (TOCTOU). Best-effort discovery (reads only): if there is no provision client or@@ -824,7 +856,8 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {const lines = removals.map((o) => ` • ${o.label} — ${o.detail}`);// --authorize names one change it consents to and never approves a removal on this list, so a run that was given one is// told so: otherwise "without --allow-destructive" reads as if the key it was given had been ignored.- const authorizeGiven = [opts.authorizedDestructive, opts.authorizedAdoption, opts.authorizedOverwrite, opts.authorizedWebResourceAdoption, opts.authorizedWebResourceOverwrite, opts.publicationRisk, opts.configurationApprovals]+ const authorizeGiven = [opts.authorizedDestructive, opts.authorizedAdoption, opts.authorizedOverwrite, opts.authorizedWebResourceAdoption, opts.authorizedWebResourceOverwrite, opts.publicationRisk, opts.configurationApprovals,+ ...(opts.commandStateApprovals ? [opts.commandStateApprovals.rows, opts.commandStateApprovals.tables] : [])].some((s) => s && s.size > 0);const msg = `refusing ${removals.length} destructive operation(s) without --allow-destructive${authorizeGiven ? ' (the --authorize keys given approve none of them)' : ''}:\n${lines.join('\n')}`;if (opts.workspaceDir) {@@ -982,6 +1015,10 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {// to this store and builds the configuration hookup over, and the maker's adopt:<configuration kind>:... row approvals....(deps.managedCreateGate ? { managedCreateGate: deps.managedCreateGate } : {}),...(opts.configurationApprovals ? { configurationApprovals: opts.configurationApprovals } : {}),+ // commandStates: the exact --authorize tokens of the feature, the raw client its rows are read and written through, and the invocation's observer.+ ...(opts.commandStateApprovals ? { commandStateApprovals: opts.commandStateApprovals } : {}),+ ...(deps.commandStateClient ? { commandStateClient: deps.commandStateClient } : {}),+ ...(commandStateObserver ? { commandStateObserver } : {}),sdk: deps.sdk,provisionSdk: deps.provisionSdk,owedLengths,@@ -1101,7 +1138,9 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {if (writesStopped) {halted = stoppedAfterEarlierAttempts(err, attempt, [...owedAcrossAttempts.values()], owedLengths, deps.warn);} else {- await settleOwedPublishes(deps.provisionSdk || deps.sdk, [...owedAcrossAttempts.values()].filter((t) => publicationBarrier.allowTarget(t, 'settle after a halt')), deps.warn, hadPublishPhase ? { tables: specTables(spec) } : undefined);+ // A build with commandStates (the run made the feature's observer) has the settle say a failed publish by its checked facts only.+ const settleOptions = hadPublishPhase ? { tables: specTables(spec) } : undefined;+ await settleOwedPublishes(deps.provisionSdk || deps.sdk, [...owedAcrossAttempts.values()].filter((t) => publicationBarrier.allowTarget(t, 'settle after a halt')), deps.warn, commandStateObserver ? { ...settleOptions, checked: true } : settleOptions);}if (typeof deps.warn === 'function') for (const w of publicationBarrier.withheld()) deps.warn(describeWithheld(w));// And set the name column length of a table whose debt no attempt got as far as paying (the last one halted before its data-model phase).@@ -1109,6 +1148,7 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {// A managed publish no fresh read can settle: say what the maker may decide, for the next run (offerPublicationRisk). Nothing// is recorded here: an approval is accepted only as a run starts (acceptPublicationRiskAtStart). The halt stands.offerPublicationRisk(halted, { say: deps.warn || log });+ reportCommandStatesOfHalt(err, halted, deps.warn || log);if (journal) journal.close({ status: 'halt', phase: halted && halted.phase, code: halted && halted.code, recoverable: !!(halted && halted.recoverable), message: String((halted && halted.message) || halted), ...counts });throw halted;}@@ -1138,9 +1178,11 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {? `\n▢ dry run — ${parts.join(', ')} (${r.planItems.length} steps). ${closing}`: `\n▢ dry run — ${r.planItems.length} steps, spec-only (no live probe; --no-live-plan)${wouldHalt ? `, ${wouldHalt} would stop the build` : ''}${removing ? `, ${removing}` : ''}. ${closing}`);if (r.pushPreview) printPushPreview(r.pushPreview, log);+ if (r.commandStatePlan) printCommandStatePlan(r.commandStatePlan, log);}if (opts.apply && r && r.ok && !r.dryRun) {log(`\n✓ build complete — ${counts.ok} created, ${counts.skip} skipped, ${counts.error} failed (${counts.ok + counts.skip + counts.error} steps)`);+ if (r.commandStates) printCommandStateResult(r.commandStates, log);// Auto-verify: reconcile the spec against what actually deployed so a silent partial build// (an artifact created but not wired, or a phase that quietly produced nothing) surfaces now// instead of only when the user opens the app. Read-only; injected (deps.verify) so tests drive it.@@ -1279,6 +1321,57 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {// result (it can quote a record value), and a failure's `error` is already reduced to its code, HTTP status and// fixed words (readonly-operations.js findingOf). Every item the preview did not answer is printed, by its reason,// and a preview that did not answer them all says so — it must never read as covering the plan when it does not.+// commandStates, as a dry run plans them (sdk-build.js planCommandStatesForDryRun): each row's stored and declared flags, and every exact+// --authorize token an apply would need — a row token for each change, and a table token for each table the apply publishes.+function printCommandStatePlan(plan, log) {+ if (plan.status !== 'planned') {+ log(`\n▢ command states — ${plan.status}: ${plan.reason}`);+ return;+ }+ const changes = plan.rows.filter((row) => row.approval);+ log(`\n▢ command states — ${plan.rows.length} row(s), ${changes.length} to change, ${plan.tables.length} table(s) to publish (an apply needs --publish)`);+ for (const row of plan.rows) {+ log(` ${row.approval ? '~' : '='} ${row.description}${row.approval ? `\n --authorize ${row.approval}${row.approved ? ' (given)' : ''}` : ' (no change)'}`);+ }+ for (const table of plan.tables) {+ log(` publish table ${table.entity}: publishes ALL saved customizations on it (anyone's), not only these buttons\n --authorize ${table.token}${table.approved ? ' (given)' : ''}`);+ }+}++// commandStates after an apply: each row's outcome and its history, worded from the row's facts (lib/command-state-run.js ROW_MESSAGES), and each+// declared table's publication, in fixed words.+function printCommandStateResult(states, log) {+ const { ROW_MESSAGES } = require('./lib/command-state-run.js');+ for (const row of states.rows || []) {+ log(` ${ROW_MESSAGES.resultLine(row)}`);+ }+ for (const table of states.publication || []) {+ log(` command-state table ${table.entity}: publication ${table.outcome}${table.reason ? ` (${table.reason})` : ''}`);+ }+}++// What a halt leaves of the command states (sdk-build.js runSdkBuildAttempt: not enumerable, so never in a serialized error or the journal):+// moved onto the halt this run reports when that is another error, then said — which rows were written, and which tables are saved and not+// published. The halt's own code, message and retry policy are left as they are. An approval halt's exact --authorize tokens are not in its+// message, which the build journal stores; they ride on it as `approvalDisplay` (lib/command-state-run.js withApprovalDisplay) and are said+// here, to the console only.+function reportCommandStatesOfHalt(err, halted, say) {+ if (!err || typeof err !== 'object') return;+ const display = err.approvalDisplay || (halted && typeof halted === 'object' ? halted.approvalDisplay : undefined);+ if (display) say(display);+ const states = err.commandStates;+ const publication = err.commandStatePublicationError;+ if (!states && !publication) return;+ if (halted && typeof halted === 'object' && halted !== err) {+ try {+ if (states) Object.defineProperty(halted, 'commandStates', { value: states, enumerable: false, configurable: true, writable: true });+ if (publication) Object.defineProperty(halted, 'commandStatePublicationError', { value: publication, enumerable: false, configurable: true, writable: true });+ } catch { /* a frozen halt carries nothing; the lines below still say it */ }+ }+ if (states) printCommandStateResult(states, say);+ if (publication) say(`${publication.code}: ${publication.message}`);+}+const PREVIEW_REASON_WORDS = Object.freeze({noTypedTarget: 'the build has no typed change for it to preview',livePlanUnknown: 'its live state could not be read',@@ -1429,7 +1522,10 @@ function authorizationKeys(argv, spec) {// back as the one argument a hint asks for; it is refused by name here rather than read as a view or chart name by the patterns below.const hasNul = (k) => typeof k === 'string' && k.includes('\u0000');const nulKeys = raw.filter(hasNul);- const configuration = configurationAuthorizationKeys(raw.filter((k) => !hasNul(k)), spec);+ // commandStates' tokens (overwrite:command-state:..., publish:command-state-table:...) are claimed before them, and a token in either+ // family that names no declared row or table is refused (lib/command-state-contract.js); the rest go on exactly as before.+ const commandStates = commandStateAuthorizationKeys(raw.filter((k) => !hasNul(k)), spec);+ const configuration = configurationAuthorizationKeys(commandStates.rest, spec);const keys = new Set(configuration.keys);const adopt = new Set();// overwrite:<configuration kind>:<declared key> (a protected item's local copy, lib/configuration-protected.js) is claimed and checked@@ -1444,6 +1540,7 @@ function authorizationKeys(argv, spec) {: code === 'CONFIGURATION_ADOPT_INVALID'? `'${token}' is not adopt:<kind>:<declared key> or adopt:<child kind>:<declared key>/<declared child>, as a configuration stop prints it`: `'${token}' is not <kind>:<declared key>:<field> for a field a configuration change can consent to`)));+ problems.push(...commandStates.problems);// The ids each approval family's artifacts carry in this spec. A view's or chart's is the reconcile's intent key, `<table>/<name>`// with the table in lower case (a spec whose declared artifact does not compile fails validation before any key is used); a Quick// Find view's (entities[].quickFind, lib/quick-find.js) is its table, in lower case.@@ -1687,7 +1784,7 @@ function authorizationKeys(argv, spec) {const i = problems.findIndex((p) => p.startsWith(`'${key}' `));if (i >= 0) problems[i] += ` — ${hint}`;}- return { keys, adopt, overwrite, webResourceAdopt, webResourceOverwrite, publicationRisk, configurationApprovals: configuration.rowApprovals || new Set(), error: problems.length ? `--authorize: ${problems.join('; ')}` : null };+ return { keys, adopt, overwrite, webResourceAdopt, webResourceOverwrite, publicationRisk, configurationApprovals: configuration.rowApprovals || new Set(), commandStateRows: commandStates.rows, commandStateTables: commandStates.tables, error: problems.length ? `--authorize: ${problems.join('; ')}` : null };}function parseLanguageCode(value) {@@ -1915,6 +2012,7 @@ async function main() {...(authorization.webResourceOverwrite.size ? { authorizedWebResourceOverwrite: authorization.webResourceOverwrite } : {}),...(authorization.publicationRisk.size ? { publicationRisk: authorization.publicationRisk } : {}),...(authorization.configurationApprovals.size ? { configurationApprovals: authorization.configurationApprovals } : {}),+ ...(authorization.commandStateRows.size || authorization.commandStateTables.size ? { commandStateApprovals: { rows: authorization.commandStateRows, tables: authorization.commandStateTables } } : {}),nonInteractive: flags['non-interactive'] === true || envTruthy(process.env.POWER_PLATFORM_SKILLS_NONINTERACTIVE),languageCode,appDir: path.dirname(specPath),@@ -2051,7 +2149,8 @@ async function runBuildCommand({ env, spec, languageCode, changedOnly, workspace// is loaded, so such a build sends, prints and loads exactly what it did before. The engine binds it to the binding store.const managedCreateGate = opts.apply && protectedConfigurationInPlay(spec, { apply: true, env, workspaceDir, appDir: opts.appDir })? require('./lib/managed-create-transport.js').createDeferredManagedCreateGate() : null;- const { sdk, provisionSdk, cleanup, isolatedReader, folderNote, previewHttpClient } = await makeSdk(env, spec, workspaceDir, authoringLanguageCode, { persistent: opts.apply, throttle, previewPush: opts.previewPush === true && !opts.apply, publicationBarrier, sendObserver, ...(workflowEffectGate ? { workflowEffectGate } : {}), ...(managedCreateGate ? { managedCreateGate } : {}) });+ const made = await makeSdk(env, spec, workspaceDir, authoringLanguageCode, { persistent: opts.apply, throttle, previewPush: opts.previewPush === true && !opts.apply, publicationBarrier, sendObserver, ...(workflowEffectGate ? { workflowEffectGate } : {}), ...(managedCreateGate ? { managedCreateGate } : {}) });+ const { sdk, provisionSdk, cleanup, folderNote, previewHttpClient, commandStateClient } = made;if (folderNote) process.stderr.write(`⚠ ${folderNote}\n`);// Durable build journal (apply runs only): a per-run record of steps + where a run halted,// written to <workspace>/build-log.jsonl. Resume = re-run the same command (idempotent).@@ -2107,6 +2206,7 @@ async function runBuildCommand({ env, spec, languageCode, changedOnly, workspacelog: (m) => process.stderr.write(m + '\n'),warn: (m) => process.stderr.write(`⚠ ${m}\n`),sdk, provisionSdk, journal, throttle, stepTally, publicationBarrier, sendObserver,+ ...(commandStateClient ? { commandStateClient } : {}),...(workflowEffectGate ? { workflowEffectGate } : {}),...(managedCreateGate ? { managedCreateGate } : {}),...(previewHttpClient ? { previewHttpClient } : {}),@@ -2121,7 +2221,7 @@ async function runBuildCommand({ env, spec, languageCode, changedOnly, workspace// would be left holding a copy of every page read — removed as soon as this verify ends.const genpage = makeGenpageSdk(env, { throttle });try {- return await verifySpec(s, readerFor(provisionSdk, appUniqueName(s), { genpage, workspaceDir, isolatedReader }), verifyOpts);+ return await verifySpec(s, inlineVerifyReader(made, s, { genpage, workspaceDir }), verifyOpts);} finally {// Awaited: a read the pass gave up on can still be running, and the workspace is removed only once the storage calls it had under way have settled. A folder it could not// remove holds page source, so it is a warning: the verify result is not changed by it.@@ -2198,4 +2298,4 @@ if (require.main === module) {emitResult(false, err);});}-module.exports = { buildModelApp, authorizationKeys, planFor, isTransientHalt, checkCollisions, discoverOpDiffState, envTruthy, parseLanguageCode, assertSnapshotInvalidated, persistAppliedBaseline, completionFor, reportCompletion };+module.exports = { buildModelApp, inlineVerifyReader, authorizationKeys, planFor, isTransientHalt, checkCollisions, discoverOpDiffState, envTruthy, parseLanguageCode, assertSnapshotInvalidated, persistAppliedBaseline, completionFor, reportCompletion };diff --git a/plugins/model-apps/scripts/lib/app-spec-doc.js b/plugins/model-apps/scripts/lib/app-spec-doc.jsindex 1d4d34c53..979bc6868 100644--- a/plugins/model-apps/scripts/lib/app-spec-doc.js+++ b/plugins/model-apps/scripts/lib/app-spec-doc.js@@ -288,6 +288,17 @@ function surfaces(spec) {}out.push('');}+ // Existing buttons whose hidden/disabled flags the build sets (commandStates[]). Only a spec that declares some gets this section. A flag the+ // entry leaves out is one the build does not touch, so it reads "unchanged", not a value.+ const commandStates = objs(spec.commandStates);+ if (commandStates.length) {+ const flag = (v) => (v === true ? 'yes' : v === false ? 'no' : 'unchanged');+ out.push('### Existing command buttons shown or hidden', '', '| Row | Table | Bar | Scope | Hidden | Disabled |', '|---|---|---|---|---|---|');+ for (const s of commandStates) {+ out.push(`| \`${cell(s.rowId)}\` | ${cell(lc(s.entity))} | ${cell(s.location)} | ${cell(s.scope)} | ${flag(s.hidden)} | ${flag(s.disabled)} |`);+ }+ out.push('', '> Each change is applied only with approval of that exact row, and publishing its table changes the button for every app that shows the table.', '');+ }return out;}diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.jsindex bf671d2f3..28e632523 100644--- a/plugins/model-apps/scripts/lib/app-spec.js+++ b/plugins/model-apps/scripts/lib/app-spec.js@@ -3538,6 +3538,12 @@ function validateAppSpec(spec, opts = {}) {checkCmdAction(`command '${c.label}' on ${c.entity}`, c.library, c.function);}}+ // commandStates (2.24.0): the hidden / disabled state of existing modern command rows, by row id (lib/command-state-contract.js). Loaded only for a+ // spec that has the key, so every other spec validates exactly as before. Nothing here touches commands[] above: the two never share an entry.+ // The structural profile (teardown, preview) reads a spec only for what it names, so there the findings are warnings, as for configuration.+ if (Object.prototype.hasOwnProperty.call(spec, 'commandStates')) {+ (profile === 'structural' ? warnings : errors).push(...require('./command-state-contract.js').validateCommandStates(spec).errors);+ }// Declared reconciliation (2.21.0). Command keys and row pins, a table's Quick Find columns, and the kinds that do NOT take// `reconcile` in this release. Every field is optional; a spec that uses none of them gets no finding from this block.{diff --git a/plugins/model-apps/scripts/lib/apply-snapshot-store.js b/plugins/model-apps/scripts/lib/apply-snapshot-store.jsindex e8156a01b..a6fda56cb 100644--- a/plugins/model-apps/scripts/lib/apply-snapshot-store.js+++ b/plugins/model-apps/scripts/lib/apply-snapshot-store.js@@ -29,6 +29,8 @@ const { processAlive } = require('./process-owner.js');// (lib/output-redaction.js: a text cleaned as a text, bytes masked as the bytes the file gets). The leases, claims and markers this module writes hold process ids, times and random ids, and a reason built from a file// system's own words.const { redactFileData } = require('./output-redaction.js');+// The one rename that outlasts a brief Windows file lock (lib/rename-retry.js).+const { renameWithRetry } = require('./rename-retry.js');const SNAPSHOT_FILE = 'apply-snapshot.json';const LEASE_FILE = 'apply-snapshot.lock';@@ -65,7 +67,8 @@ function snapshotAbsent(workspaceDir) {// writeSync may write only part of it (see createExclusive), and a short write fsynced and renamed into// place is exactly the partial file this exists to prevent. A write that fails at any step removes its// temp and leaves the target as it was. The sitemap baseline (deployed-baseline.js) is written through it too.-function writeFileAtomic(target, text) {+// `opts.retryLock === false` makes the rename a single attempt, exactly as before lib/rename-retry.js (see below).+function writeFileAtomic(target, text, opts) {const tmp = `${target}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;try {const fd = fs.openSync(tmp, 'w');@@ -75,7 +78,18 @@ function writeFileAtomic(target, text) {} finally {fs.closeSync(fd);}- fs.renameSync(tmp, target);+ // A rename that Windows refuses for a moment (a scanner or an indexer holding the file) is repeated by default, and why+ // that is safe: it is the same rename of this call's own file (`tmp` has the pid, the time and a random part in its+ // name), and a refused rename moves nothing, so atomicity is unchanged. It is safe for the targets whose writers are+ // serialised by a lease and by the re-read and compare-and-set around the write: the apply snapshot, the managed+ // bindings, and the page, dashboard and web-resource records. Only a program that edits such a file by hand while the+ // rename is refused could be overwritten, and that edit is outside what the plugin supports (the same overwrite+ // happens if it lands just before the first attempt). It is NOT safe for a target that an unleased writer can also+ // write, because an older write that was refused could then land after a newer one: such a target passes+ // `{ retryLock: false }` and renames once (the deployed baseline, which the download writes without the build lease).+ // The wait is bounded per call and per process: see lib/rename-retry.js.+ if (opts && opts.retryLock === false) fs.renameSync(tmp, target);+ else renameWithRetry(fs, tmp, target);} catch (e) {try { fs.unlinkSync(tmp); } catch { /* best-effort cleanup of the orphaned temp */ }throw e;@@ -547,7 +561,10 @@ function markDistrusted(workspaceDir, { reason } = {}) {try {fs.mkdirSync(workspaceDir, { recursive: true });fs.writeFileSync(tmp, JSON.stringify({ id, reason: reason || null, pid: process.pid, at: new Date().toISOString() }));- fs.renameSync(tmp, target);+ // Why repeating the rename is safe here: `tmp` is this call's own file (its name holds this marker's unique id), a+ // refused rename moves nothing, and a marker is only ever created under a name nobody else uses, so a repeat cannot+ // replace another writer's file. The wait is bounded per call and per process: see lib/rename-retry.js.+ renameWithRetry(fs, tmp, target);return { ok: true };} catch (e) {try { fs.rmSync(tmp, { force: true }); } catch { /* best-effort cleanup of the temp */ }@@ -679,6 +696,10 @@ function clearWorkspace(target, deps = {}) {reserved = true;if (typeof deps.beforeRename === 'function') deps.beforeRename();const candidate = `${target}.cleared-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;+ // One attempt, on purpose (lib/rename-retry.js is not used here): the preflight and the lease were taken for the+ // folder as it is NOW, and waiting would let a program that is not part of the lease (an editor, a sync client)+ // swap another folder in under the same path, which would then be moved and deleted on this approval. A refusal+ // is reported as it is, and the caller keeps the folder.fs.renameSync(target, candidate);aside = candidate;} catch (e) {diff --git a/plugins/model-apps/scripts/lib/changed-only-flow.js b/plugins/model-apps/scripts/lib/changed-only-flow.jsindex e6d61e5a9..8bdc1af71 100644--- a/plugins/model-apps/scripts/lib/changed-only-flow.js+++ b/plugins/model-apps/scripts/lib/changed-only-flow.js@@ -31,9 +31,11 @@ const { odataLit } = require('./odata.js');// The app's build lease (lib/app-operation-lease.js), and the one derivation of the app's unique name it is keyed by.const { withAppBuildLease, applyWorkspaceOf } = require('./app-operation-lease.js');const { appUniqueName } = require('./sdk-build.js');+const { usesCommandStates } = require('./command-state-contract.js');// Why a changed-only apply runs whole while protected configuration is in play (the decision's reason, printed and in the result).const PROTECTED_CONFIGURATION_FULL = 'protected configuration is in play (configurationIdentity "stable-v1", or configuration state in the binding store) — full build, so its checks run before any write and its changes are applied';+const COMMAND_STATES_FULL = 'the spec declares commandStates — full build, so every declared command row is read and its change approved before any write';// ---- PURE decision ------------------------------------------------------------------------------------@@ -342,6 +344,11 @@ async function runChangedOnlyApplyHeld({ spec, opts, deps }) {if (deps.managedCreateGate && (decision.decision === 'fast' || decision.decision === 'noop')) {decision = { ...decision, decision: 'full', reason: PROTECTED_CONFIGURATION_FULL };}+ // commandStates are applied only by a full build (lib/command-state-run.js commandStateMode): it reads every declared row and asks for+ // approval of what it finds, which the snapshot cannot stand in for — a row edited in the designer since leaves the spec unchanged.+ if (usesCommandStates(spec) && (decision.decision === 'fast' || decision.decision === 'noop')) {+ decision = { ...decision, decision: 'full', reason: COMMAND_STATES_FULL };+ }log(`▸ changed-only: ${decision.decision.toUpperCase()} — ${decision.reason}`);if (decision.decision === 'noop') {@@ -546,4 +553,5 @@ module.exports = {fullApplyOpts,distrustWorkspace,PROTECTED_CONFIGURATION_FULL,+ COMMAND_STATES_FULL,};diff --git a/plugins/model-apps/scripts/lib/classify-changes.js b/plugins/model-apps/scripts/lib/classify-changes.jsindex dd0839af6..c28ba5e6a 100644--- a/plugins/model-apps/scripts/lib/classify-changes.js+++ b/plugins/model-apps/scripts/lib/classify-changes.js@@ -207,6 +207,24 @@ function classifyForms(cur, prior) {return out;}+// commandStates[]: matched by row id. Every change is applied by a full build, which reads each declared row and asks for approval of what it+// finds (lib/command-state-run.js), so none is debt. An entry no longer declared leaves its row's flags as they are: that is not a divergence+// a later build could close either, so it is said and not recorded.+function classifyCommandStates(cur, prior) {+ const out = { fast: [], full: [], debt: [] };+ const byRow = (list) => new Map((Array.isArray(list) ? list : []).map((e) => [String((e && e.rowId) || '').toLowerCase(), e]));+ const now = byRow(cur.commandStates);+ const before = byRow(prior.commandStates);+ for (const [id, entry] of now) {+ if (!before.has(id)) out.full.push(`commands: command state of row '${id}' added — applied by a full build`);+ else if (stableStringify(entry) !== stableStringify(before.get(id))) out.full.push(`commands: command state of row '${id}' changed — applied by a full build`);+ }+ for (const id of before.keys()) {+ if (!now.has(id)) out.full.push(`commands: command state of row '${id}' no longer declared — a build leaves the row's flags as they are`);+ }+ return out;+}+// THE classifier. `current` / `prior` are ANNOTATED specs. Returns:// { verdict:'noop'|'fast'|'full', changedPhases, fastChanges, fullReasons, debt }// verdict 'fast' ⇒ every changed phase yielded a convergent shape (fastChanges) and there are no@@ -234,7 +252,7 @@ function classifyChanges(current, prior) {case 'app-shell': merge(classifyAppShell(cur, prior)); break;case 'forms': merge(classifyForms(cur, prior)); break;case 'charts': merge(classifyAdditive(cur, prior, 'charts', 'chart', 'charts')); break;- case 'commands': merge(classifyAdditive(cur, prior, 'commands', 'command', 'commands')); break;+ case 'commands': merge(classifyAdditive(cur, prior, 'commands', 'command', 'commands')); merge(classifyCommandStates(cur, prior)); break;case 'dashboards': merge(classifyAdditive(cur, prior, 'dashboards', 'dashboard', 'dashboards')); break;case 'web-resources': merge(classifyAdditive(cur, prior, 'web-resources', 'webResource', 'webResources')); break;// Both are additive discover-reconcile: the engine creates what is missing and does NOT reapplydiff --git a/plugins/model-apps/scripts/lib/command-state-contract.js b/plugins/model-apps/scripts/lib/command-state-contract.jsnew file mode 100644index 000000000..d887d1894--- /dev/null+++ b/plugins/model-apps/scripts/lib/command-state-contract.js@@ -0,0 +1,438 @@+'use strict';+// The fixed vocabulary of a modern command button's row state: which command bars a row can sit on, what a row id and a row version look like,+// and why a row is or is not a candidate for a row-state edit. Pure: no request, no file, no clock.+//+// A modern command is an `appaction` row. Its `location` is a choice whose public values are+// 0 Form, 1 Main Grid, 2 Sub Grid, 3 Associated Grid, 4 Quick Form, 5 Global Header, 6 Dashboard+// (https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/appaction). The App Spec names the first three the way+// `commands[].location` already does — MainTab, HomeTab, ContextualTab — and no other: a row on another bar is shown by its number and is+// never mapped onto a supported one.++const { FORM_GUID_RE } = require('./app-spec.js');++// The App Spec's name of a bar -> the row's `location` value, and back.+const LOCATION_BY_BAR = Object.freeze({ MainTab: 0, HomeTab: 1, ContextualTab: 2 });+const BAR_BY_LOCATION = Object.freeze({ 0: 'MainTab', 1: 'HomeTab', 2: 'ContextualTab' });+const UNSUPPORTED_BAR = 'unsupported';++// A row's version is the weak entity tag the platform sends with the row, e.g.+// "@odata.etag": "W/\"4893215\""+// It is used exactly as it came; a version is never built from `versionnumber`, compared as a number or replaced by "*".+// See https://learn.microsoft.com/power-apps/developer/data-platform/webapi/perform-conditional-operations-using-web-api+const ROW_VERSION = /^W\/"\d+"$/;++// A row id as the App Spec and the listing write it: lower case, hyphenated, no braces, not all zeros.+const ZERO_GUID = '00000000-0000-0000-0000-000000000000';++// The columns a row is read with. Every one of them must be in the answer: a column the platform left out is not a null, and a null is not a false.+const ROW_SELECT = Object.freeze([+ 'appactionid', 'name', 'uniquename', 'buttonlabeltext', 'context', 'contextvalue', '_contextentity_value', '_appmoduleid_value', 'location',+ 'type', 'origin', 'statecode', 'statuscode', 'ismanaged', 'iscustomizable', '_parentappactionid_value', 'hidden', 'isdisabled', 'visibilitytype',+ 'visibilityformulacomponentlibrary', '_visibilityformulacomponentlibraryid_value', 'visibilityformulacomponentname', 'visibilityformulafunctionname',+ 'onclickeventtype',+]);++// Why a row is not a candidate, one word each, in the order a listing shows them. A row that is a candidate has none.+// shape-unreadable a selected column is missing, or holds a value of the wrong kind (a number as text, a null where a number belongs)+// id-mismatch the answer is another row than the one asked for+// context-not-table the command is not bound to a table (`context` is not 1, Entity)+// context-mismatch its table (by logical name or by the table's metadata id) is not the one asked for+// table-not-in-app the table is not a component of the app+// location-unsupported the bar is none of MainTab, HomeTab, ContextualTab+// location-mismatch the bar is another one than the declared one+// app-scoped the row is scoped to an app (this one or another), not to its table: only table-scoped rows are edited in this version+// not-standard-button a drop-down, split button or group, not a plain button (`type` 0)+// nested the button sits inside another (it has a parent)+// not-default-origin migrated from the classic ribbon (`origin` is not 0, Default)+// inactive the row is deactivated+// managed the row came with a managed solution+// not-customizable the row is marked not customizable+// flags-unreadable `hidden` or `isdisabled` is not a true or a false+// visibility-formula the button's visibility is a Power Fx formula or classic rules (`visibilitytype` other than null or 0, or a formula field set)+// formula-action its on-click is a Power Fx formula+// version-unavailable no usable row version: optimistic concurrency is off for the table of commands, or the row came without its version+const REASONS = Object.freeze([+ 'shape-unreadable', 'id-mismatch', 'context-not-table', 'context-mismatch', 'table-not-in-app', 'location-unsupported', 'location-mismatch',+ 'app-scoped', 'not-standard-button', 'nested', 'not-default-origin', 'inactive', 'managed', 'not-customizable',+ 'flags-unreadable', 'visibility-formula', 'formula-action', 'version-unavailable',+]);++// The refusal a reason stands for, when a row-state edit meets it: the first reason that applies decides.+const CODE_BY_REASON = Object.freeze({+ 'shape-unreadable': 'command-state-row-unreadable',+ 'flags-unreadable': 'command-state-row-unreadable',+ 'id-mismatch': 'command-state-target-mismatch',+ 'context-not-table': 'command-state-target-mismatch',+ 'context-mismatch': 'command-state-target-mismatch',+ 'location-mismatch': 'command-state-target-mismatch',+ 'location-unsupported': 'command-state-target-mismatch',+ 'app-scoped': 'command-state-app-scope-unverified',+ 'table-not-in-app': 'command-state-context-unverified',+ 'not-standard-button': 'command-state-target-unsupported',+ nested: 'command-state-target-unsupported',+ 'not-default-origin': 'command-state-target-unsupported',+ inactive: 'command-state-target-unsupported',+ managed: 'command-state-target-unsupported',+ 'not-customizable': 'command-state-target-unsupported',+ 'visibility-formula': 'command-state-target-unsupported',+ 'formula-action': 'command-state-target-unsupported',+ 'version-unavailable': 'command-state-version-unavailable',+});+// Unreadable outranks mismatch, mismatch outranks unsupported: a row that cannot be read cannot be said to be the wrong one. An app-scoped row is+// refused for its scope before anything else is said about it: app scope is not supported in this version, whichever app the row belongs to.+const CODE_ORDER = ['command-state-row-unreadable', 'command-state-context-unverified', 'command-state-app-scope-unverified', 'command-state-target-mismatch', 'command-state-target-unsupported', 'command-state-version-unavailable'];++function codeForReasons(reasons) {+ const codes = new Set((reasons || []).map((reason) => CODE_BY_REASON[reason]).filter(Boolean));+ return CODE_ORDER.find((code) => codes.has(code)) || null;+}++// A row id in the one spelling this feature uses, or null when the text is not one: braces are not taken off here, because the App Spec+// writes ids without them and a listing prints them without them; the platform's answers are normalised with `guidOf`.+function canonicalRowId(text) {+ if (typeof text !== 'string' || text !== text.toLowerCase() || !FORM_GUID_RE.test(text) || text === ZERO_GUID) return null;+ return text;+}++// A GUID the platform answered, in lower case without braces, or null when the value is no GUID.+// "_appmoduleid_value": "{5F0D3A2B-...}" or "5f0d3a2b-..." or null+function guidOf(value) {+ if (typeof value !== 'string') return null;+ const key = value.replace(/^\{|\}$/g, '').toLowerCase();+ return FORM_GUID_RE.test(key) ? key : null;+}++class CommandStateError extends Error {+ constructor(code, message, detail) {+ super(message);+ this.name = 'CommandStateError';+ this.code = code;+ if (detail !== undefined) this.detail = detail;+ }+}++// ---------------------------------------------------------------------------------------------------------------------------------------------+// The one way this feature says what was wrong with an answer of the service: a failed read, a refused write, an answer it could not use.+// The design of row-state edits does not let ETags, digests, handlers or raw responses into a halt, a journal or a verify detail, and the+// service's free text can carry any of them. A refusal is answered as, e.g.+// HTTP 403 { "error": { "code": "0x80040220", "message": "Principal user (Id=...) is missing prvReadAppAction privilege ..." } }+// and a malformed answer can hold anything in any field (a row id that is no GUID, a next-page link to anywhere). So the text below is built+// only from values that are checked here, each dropped when it is not of its shape, and fixed words:+// status an HTTP status, an integer+// dataverseCode `0x` and 8 hex digits, said in lower case: https://learn.microsoft.com/power-apps/developer/data-platform/reference/web-service-error-codes+// systemCode a system error code of a read with no answer at all (ECONNRESET), upper case letters, digits and `_`+// field the NAME of a field the answer got wrong, one of SERVICE_FIELDS — never its value+// problem one of SERVICE_PROBLEMS+// Every CommandStateError that says something about an answer is worded here; every other one is fixed text and values the feature checked+// itself (a row id, a table name, a bar), so a CommandStateError's message is safe to journal. tests/command-state-taint.test.js plants a+// marker in every service string a build, a listing and a verify read, and proves it reaches none of them.+const DATAVERSE_CODE = /^0x[0-9a-f]{8}$/i;+const SYSTEM_CODE = /^[A-Z][A-Z0-9_]{2,63}$/;+const SERVICE_FIELDS = new Set([+ ...ROW_SELECT, '@odata.etag', '@odata.nextLink', 'value', 'appmoduleid', 'appmoduleidunique', 'componentstate', 'objectid', 'componenttype',+ 'MetadataId', 'EntitySetName', 'LogicalName', 'IsOptimisticConcurrencyEnabled',+]);+const RUN_AGAIN = 'run it again, and if it persists check the environment\'s answer for this read';+const SERVICE_PROBLEMS = Object.freeze({+ // A read that was answered with an error status, or not answered: said by the facts alone (see serviceAnswerText).+ failed: null,+ 'write-refused': null,+ // A table publication (PublishXml) that was refused or not answered: said by the facts alone, like a refused write.+ 'publish-refused': null,+ 'not-a-list': `the answer is not a list of rows; ${RUN_AGAIN}`,+ 'not-a-record': `the answer holds something that is not a record; ${RUN_AGAIN}`,+ 'repeated-link': `the answer repeated a next-page link; ${RUN_AGAIN}`,+ 'malformed-link': `the answer's next-page link is not a link; ${RUN_AGAIN}`,+ 'link-outside': 'the next-page link pointed outside the expected API and was not followed',+ 'malformed-field': `the answer holds an unreadable value; ${RUN_AGAIN}`,+ unplaceable: `the answer holds a row that cannot be placed; ${RUN_AGAIN}`,+ 'layer-ambiguous': `the answer does not name exactly one current layer of the app; ${RUN_AGAIN}`,+ unexpected: `the answer could not be read; ${RUN_AGAIN}`,+});++/**+ * @param {{ problem?: string, status?: number, dataverseCode?: string, systemCode?: string, field?: string|string[] }} facts+ * @returns {string} e.g. "HTTP 403, Dataverse error 0x80040220; check that the signed-in account can read it, and look the error code up"+ * or "no usable answer (ECONNRESET); check the connection and run it again"+ * or "the answer holds an unreadable value (objectid); run it again, ..."+ * or, for 'publish-refused', "PublishXml answered HTTP 503, Dataverse error 0x80040220" (the warning around it says the remedy)+ */+function serviceAnswerText({ problem = 'failed', status, dataverseCode, systemCode, field } = {}) {+ const facts = [];+ if (Number.isInteger(status)) facts.push(`HTTP ${status}`);+ if (typeof dataverseCode === 'string' && DATAVERSE_CODE.test(dataverseCode)) facts.push(`Dataverse error ${dataverseCode.toLowerCase()}`);+ const said = facts.join(', ');+ if (problem === 'write-refused') return said ? `the platform refused the write (${said})` : 'the platform refused the write';+ const system = typeof systemCode === 'string' && SYSTEM_CODE.test(systemCode) ? ` (${systemCode})` : '';+ if (problem === 'publish-refused') return said ? `PublishXml answered ${said}` : `PublishXml got no usable answer${system}`;+ if (!Object.prototype.hasOwnProperty.call(SERVICE_PROBLEMS, problem)) problem = 'unexpected';+ if (problem === 'failed') {+ if (said) return `${said}; check that the signed-in account can read it, and look the error code up`;+ return `no usable answer${system}; check the connection and run it again`;+ }+ const fields = (Array.isArray(field) ? field : [field]).filter((name) => typeof name === 'string' && SERVICE_FIELDS.has(name));+ const [what, remedy] = SERVICE_PROBLEMS[problem].split('; ');+ return `${what}${fields.length ? ` (${fields.join(', ')})` : ''}${remedy ? `; ${remedy}` : ''}`;+}++// What a halt says about an error a build with commandStates caught at a table publication (sdk-build.js createTablePublication) and+// threw on unchanged. The error stays the one thrown — its message, code, cause and status are what decide a retry (retry-policy.js+// judgeFailure reads its words), so none of them is rewritten — and this mark beside it is what the runner that turns it into a halt+// (entity-provision.js makeRunner) says instead: the checked text (serviceAnswerText) and a code that is the error's own only when it has a+// system code's shape (an SDK's CONNECTION_ERROR, ARTIFACT_NOT_FOUND), else the runner's own `sdk-error`. An error carries no mark in a+// build without commandStates, so there the halt is the one 2.23.0 made. Non-enumerable, so nothing that copies or serialises the error+// carries it; an error that cannot take it (frozen, or not an object) keeps its own words.+const CHECKED_DISPLAY = Symbol.for('model-apps.command-state.checked-display');+function withCheckedDisplay(error, text) {+ if (!error || typeof error !== 'object') return error;+ const code = typeof error.code === 'string' && SYSTEM_CODE.test(error.code) ? error.code : 'sdk-error';+ try { Object.defineProperty(error, CHECKED_DISPLAY, { value: { text: String(text), code }, enumerable: false, configurable: true }); } catch { /* keeps its own words */ }+ return error;+}+/** @returns {{ text: string, code: string }} what a halt says of `error`: its checked mark, else its own message and code. */+function checkedDisplay(error) {+ const mark = error && typeof error === 'object' ? error[CHECKED_DISPLAY] : undefined;+ if (mark) return mark;+ return { text: String((error && error.message) || error), code: (error && error.code) || 'sdk-error' };+}++// ---------------------------------------------------------------------------------------------------------------------------------------------+// The App Spec's `commandStates[]`: the hidden / disabled state of an EXISTING table-scoped modern command, named by its row id.+// { "entity": "contoso_order", "location": "MainTab", "scope": "table", "rowId": "11111111-1111-4111-8111-111111111111", "hidden": true }+// The first four keys are required, and at least one of `hidden` / `disabled`. A flag left out keeps what the row stores; `false` is an+// instruction. `disabled` is the row's `isdisabled` column.++const COMMAND_STATES_MIN_VERSION = '2.24.0';+const SPEC_INVALID = 'command-state-spec-invalid';+const APP_SCOPE_UNVERIFIED = 'command-state-app-scope-unverified';+const ENTRY_KEYS = Object.freeze(['entity', 'location', 'scope', 'rowId', 'hidden', 'disabled']);+// The App Spec's flag name -> the row's column.+const WIRE_FLAG = Object.freeze({ hidden: 'hidden', disabled: 'isdisabled' });+const SPEC_FLAG = Object.freeze({ hidden: 'hidden', isdisabled: 'disabled' });+// Keys an author may reach for from `commands[]` or the row itself. Each is an unknown field here; `isdisabled` names its spelling.+const FIELD_HINTS = Object.freeze({ isdisabled: 'use disabled' });++const own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);+const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);+const show = (value) => {+ try { return JSON.stringify(value); } catch { return String(value); }+};++/** True when the spec declares at least one command state. Absent and `[]` are the feature switched off. */+function usesCommandStates(spec) {+ return !!spec && typeof spec === 'object' && Array.isArray(spec.commandStates) && spec.commandStates.length > 0;+}++// A row id an author wrote, in the one spelling this feature uses: hex in either case is taken and lower-cased; braces, whitespace and the+// all-zero id are not.+const authoredRowId = (value) => (typeof value === 'string' ? canonicalRowId(value.toLowerCase()) : null);++/**+ * Offline checks of `spec.commandStates`. Absent: nothing to check. Every finding is one line that starts with its stable code and names the+ * entry and the reason:+ * command-state-spec-invalid: commandStates[1].location (location-invalid): ...+ * command-state-app-scope-unverified: commandStates[0].scope: ...+ * @returns {{ errors: string[], findings: { code: string, subreason: string|null, path: string, message: string }[] }}+ */+function validateCommandStates(spec) {+ const findings = [];+ const add = (code, subreason, path, message) => findings.push({ code, subreason, path, message });+ const invalid = (subreason, path, message) => add(SPEC_INVALID, subreason, path, message);+ const out = () => ({+ findings,+ errors: findings.map((f) => `${f.code}: ${f.path}${f.subreason ? ` (${f.subreason})` : ''}: ${f.message}`),+ });+ if (!spec || typeof spec !== 'object' || !own(spec, 'commandStates') || spec.commandStates === undefined) return out();+ const states = spec.commandStates;+ if (!Array.isArray(states)) {+ invalid('array-required', 'commandStates', `must be an array of command states (or left out); got ${show(states)}`);+ return out();+ }+ if (!states.length) return out();+ // The App Spec's declared tables by logical name (the schema name in lower case), the way commands[] and the build name them.+ const declared = new Set();+ for (const e of Array.isArray(spec.entities) ? spec.entities : []) {+ if (e && typeof e.schemaName === 'string' && e.schemaName.trim()) declared.add(e.schemaName.toLowerCase());+ }+ const seen = new Map();+ states.forEach((entry, i) => {+ const at = `commandStates[${i}]`;+ if (!isRecord(entry)) {+ invalid('object-required', at, `must be an object; got ${Array.isArray(entry) ? 'an array' : show(entry)}`);+ return;+ }+ for (const key of Object.keys(entry)) {+ if (ENTRY_KEYS.includes(key)) continue;+ const hint = FIELD_HINTS[key] ? ` (${FIELD_HINTS[key]})` : '';+ invalid('unknown-field', `${at}.${key}`, `is not a command-state field${hint}; a command state takes only ${ENTRY_KEYS.join(', ')}. `+ + 'It changes the hidden or disabled state of an existing button and nothing else about it');+ }+ if (typeof entry.entity !== 'string' || !declared.has(entry.entity.toLowerCase())) {+ invalid('entity-undeclared', `${at}.entity`, `must name a table declared in entities[]; got ${show(entry.entity)}`);+ }+ if (typeof entry.location !== 'string' || !own(LOCATION_BY_BAR, entry.location)) {+ invalid('location-invalid', `${at}.location`, `must be exactly MainTab, HomeTab or ContextualTab; got ${show(entry.location)}`);+ }+ if (entry.scope === 'app') {+ add(APP_SCOPE_UNVERIFIED, null, `${at}.scope`, 'app-scoped command rows are not supported in this version; only scope "table" is');+ } else if (entry.scope !== 'table') {+ invalid('scope-invalid', `${at}.scope`, `must be exactly "table"; got ${show(entry.scope)}`);+ }+ const rowId = authoredRowId(entry.rowId);+ if (!rowId) {+ invalid('row-id-invalid', `${at}.rowId`, `must be a row id like 11111111-1111-4111-8111-111111111111 (no braces, not all zeros); got ${show(entry.rowId)}. `+ + 'List the app\'s buttons with list-command-states.js to find it');+ } else if (seen.has(rowId)) {+ invalid('row-id-duplicate', `${at}.rowId`, `names the same row as commandStates[${seen.get(rowId)}]; give each row one entry with all its flags`);+ } else {+ seen.set(rowId, i);+ }+ for (const flag of ['hidden', 'disabled']) {+ if (own(entry, flag) && typeof entry[flag] !== 'boolean') invalid('boolean-required', `${at}.${flag}`, `must be true or false; got ${show(entry[flag])}`);+ }+ if (!own(entry, 'hidden') && !own(entry, 'disabled')) invalid('flags-required', at, 'must set hidden, disabled or both');+ });+ if (!spec.app || typeof spec.app.uniqueName !== 'string' || !spec.app.uniqueName.trim()) {+ invalid('app-unique-name-required', 'app.uniqueName', 'commandStates needs the app\'s unique name, which is how the build finds the app the buttons are checked against');+ }+ // Required here, not at the top: app-spec.js loads this module lazily from inside validateAppSpec, so its exports are complete by now.+ const { isPluginVersion, compareVersions } = require('./app-spec.js');+ const floor = spec.minimumPluginVersion;+ if (!isPluginVersion(floor) || compareVersions(floor, COMMAND_STATES_MIN_VERSION) < 0) {+ invalid('version-floor-required', 'minimumPluginVersion', `must be '${COMMAND_STATES_MIN_VERSION}' or newer when commandStates is used, so an older plugin refuses the spec rather than ignoring it`);+ }+ return out();+}++/**+ * One valid entry in the form the build uses. Call only on a spec validateCommandStates found nothing wrong with.+ * @returns {{ entity: string, bar: string, location: number, scope: 'table', rowId: string, desired: { hidden?: boolean, isdisabled?: boolean } }}+ */+function normalizeCommandState(entry) {+ return {+ entity: entry.entity.toLowerCase(),+ bar: entry.location,+ location: LOCATION_BY_BAR[entry.location],+ scope: 'table',+ rowId: authoredRowId(entry.rowId),+ desired: wireDesired(entry),+ };+}++/** Every entry, normalized, in the spec's order; [] when the feature is off. */+function normalizeCommandStates(spec) {+ return usesCommandStates(spec) ? spec.commandStates.map(normalizeCommandState) : [];+}++/** The flags an entry sets, by the row's column name: { hidden?: boolean, isdisabled?: boolean }. A flag left out is not in it. */+function wireDesired(entry) {+ const desired = {};+ for (const flag of ['hidden', 'disabled']) if (own(entry, flag) && typeof entry[flag] === 'boolean') desired[WIRE_FLAG[flag]] = entry[flag];+ return desired;+}++/**+ * The PATCH body: only the declared flags whose stored value differs, by column name. `false` is kept: it is an instruction.+ * @param {{ hidden?: boolean, isdisabled?: boolean }} desired+ * @param {{ hidden: boolean, isdisabled: boolean }} stored+ */+function diffCommandFlags(desired, stored) {+ const delta = {};+ for (const key of ['hidden', 'isdisabled']) if (own(desired, key) && desired[key] !== stored[key]) delta[key] = desired[key];+ return delta;+}++// The environment's origin as an approval names it: https and the host in lower case, no path. Anything else is no origin.+function canonicalOrigin(value) {+ let url;+ try { url = new URL(String(value)); } catch { return null; }+ return url.protocol === 'https:' ? url.origin.toLowerCase() : null;+}++function digest(value) {+ const { canonicalJson } = require('./reconcile-common.js');+ const { sha256 } = require('./hash.js');+ return sha256(canonicalJson(value));+}++const ROW_TOKEN_PREFIX = 'overwrite:command-state:';+const TABLE_TOKEN_PREFIX = 'publish:command-state-table:';++/**+ * The approval for one row-state change: one observed version of one row under one intent.+ * overwrite:command-state:<entity>/<bar>/<rowId>/<sha256>+ * The digest is the SHA-256 of the canonical JSON of+ * { contract: "command-state-v1", origin, appId, tableId, entity, location: 0|1|2, scope: "table", rowId, ifMatch, desired }+ * so a new version of the row, another environment, app or table incarnation, or another intent each needs a new approval.+ */+function commandStateApprovalKey({ origin, appId, tableId, entity, location, rowId, ifMatch, desired }) {+ const hash = digest({+ contract: 'command-state-v1',+ origin: canonicalOrigin(origin),+ appId: guidOf(appId),+ tableId: guidOf(tableId),+ entity: String(entity).toLowerCase(),+ location,+ scope: 'table',+ rowId: guidOf(rowId),+ ifMatch,+ desired: { ...desired },+ });+ return `${ROW_TOKEN_PREFIX}${String(entity).toLowerCase()}/${BAR_BY_LOCATION[location]}/${guidOf(rowId)}/${hash}`;+}++/**+ * The approval to publish a table's saved customizations — ALL of them, not one row:+ * publish:command-state-table:<entity>/<sha256 of { contract: "command-table-publish-v1", origin, appId, tableId, entity }>+ */+function commandTablePublishApprovalKey({ origin, appId, tableId, entity }) {+ const hash = digest({+ contract: 'command-table-publish-v1', origin: canonicalOrigin(origin), appId: guidOf(appId), tableId: guidOf(tableId), entity: String(entity).toLowerCase(),+ });+ return `${TABLE_TOKEN_PREFIX}${String(entity).toLowerCase()}/${hash}`;+}++const ROW_TOKEN = /^overwrite:command-state:([a-z][a-z0-9_]*)\/(MainTab|HomeTab|ContextualTab)\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/([0-9a-f]{64})$/;+const TABLE_TOKEN = /^publish:command-state-table:([a-z][a-z0-9_]*)\/([0-9a-f]{64})$/;++/** True for a `--authorize` value this feature claims: the two families above, spelled any way, so a malformed one is refused rather than read as a view's. */+const isCommandStateToken = (token) => typeof token === 'string'+ && (token.toLowerCase().startsWith(ROW_TOKEN_PREFIX) || token.toLowerCase().startsWith(TABLE_TOKEN_PREFIX));++/**+ * Claims this feature's `--authorize` values out of `raw` and checks each one's grammar against the spec's declarations. Exact tokens only:+ * no wildcard, no blanket approval, no token that names no declared row or table.+ * @returns {{ rows: Set<string>, tables: Set<string>, rest: string[], problems: string[] }}+ */+function commandStateAuthorizationKeys(raw, spec) {+ const rows = new Set();+ const tables = new Set();+ const rest = [];+ const problems = [];+ const states = (validateCommandStates(spec).errors.length ? [] : normalizeCommandStates(spec));+ const declaredRows = new Set(states.map((s) => `${s.entity}/${s.bar}/${s.rowId}`));+ const declaredTables = new Set(states.map((s) => s.entity));+ for (const token of raw) {+ if (!isCommandStateToken(token)) { rest.push(token); continue; }+ const row = ROW_TOKEN.exec(token);+ const table = row ? null : TABLE_TOKEN.exec(token);+ if (row) {+ if (!declaredRows.has(`${row[1]}/${row[2]}/${row[3]}`)) problems.push(`'${token}' names a command row that no commandStates entry declares`);+ else rows.add(token);+ } else if (table) {+ if (!declaredTables.has(table[1])) problems.push(`'${token}' names a table that no commandStates entry declares`);+ else tables.add(token);+ } else {+ problems.push(`'${token}' is not overwrite:command-state:<table>/<bar>/<row id>/<64 hex> or publish:command-state-table:<table>/<64 hex>, exactly as the build prints it`);+ }+ }+ return { rows, tables, rest, problems };+}++module.exports = {+ LOCATION_BY_BAR, BAR_BY_LOCATION, UNSUPPORTED_BAR, ROW_VERSION, ROW_SELECT, REASONS, CODE_BY_REASON,+ codeForReasons, canonicalRowId, guidOf, CommandStateError, serviceAnswerText, SERVICE_PROBLEMS, SERVICE_FIELDS, withCheckedDisplay, checkedDisplay,+ COMMAND_STATES_MIN_VERSION, WIRE_FLAG, SPEC_FLAG,+ usesCommandStates, validateCommandStates, normalizeCommandState, normalizeCommandStates, wireDesired, diffCommandFlags, canonicalOrigin,+ commandStateApprovalKey, commandTablePublishApprovalKey, commandStateAuthorizationKeys, isCommandStateToken,+};diff --git a/plugins/model-apps/scripts/lib/command-state-read.js b/plugins/model-apps/scripts/lib/command-state-read.jsnew file mode 100644index 000000000..b2fa535db--- /dev/null+++ b/plugins/model-apps/scripts/lib/command-state-read.js@@ -0,0 +1,477 @@+'use strict';+// Reads of the modern command buttons (`appaction` rows) of an app's tables, and the one strict reading of a row that says whether its+// `hidden` / `isdisabled` state is something a row-state edit may touch. Read-only: nothing here writes.+//+// Every read goes through a reader with `get(path)`, `getAbsolute(url)` and `apiUrl(path)` — lib/command-state-transport.js — so the same+// collection reader the build uses for an app's components (`collectionRows`, lib/app-components.js) reads every page, follows every+// continuation on the same origin and refuses an answer that is no list. A read that fails is an error, never a shorter list: a button that a+// failed page left out cannot be told from a button that is not there.+//+// The rows are the platform's, read with the columns of ROW_SELECT (lib/command-state-contract.js). A row is answered as, e.g.+// { "@odata.etag": "W/\"4893215\"", "appactionid": "1d6b4b1e-...", "name": "contoso_Escalate!1a2b", "uniquename": "contoso_Escalate!1a2b",+// "buttonlabeltext": "Escalate", "context": 1, "contextvalue": "contoso_project", "_contextentity_value": "8f2c...", "_appmoduleid_value": null,+// "location": 0, "type": 0, "origin": 0, "statecode": 0, "statuscode": 1, "ismanaged": false,+// "iscustomizable": { "Value": true, "CanBeChanged": true, "ManagedPropertyLogicalName": "iscustomizableanddeletable" },+// "_parentappactionid_value": null, "hidden": false, "isdisabled": false, "visibilitytype": null, "visibilityformulacomponentlibrary": null,+// "_visibilityformulacomponentlibraryid_value": null, "visibilityformulacomponentname": null, "visibilityformulafunctionname": null,+// "onclickeventtype": 2 }+// The choice values are the public ones: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/appaction+// Scope: `_appmoduleid_value` null is a TABLE-scoped command (every app that shows the table renders it), an app id an APP-scoped one —+// https://learn.microsoft.com/power-apps/maker/model-driven-apps/commanding-scopes++const { collectionRows, currentAppLayer, appComponentRows, tableRefs, TABLE_NAME } = require('./app-components.js');+const { odataLit } = require('./odata.js');+const { compareText } = require('./compare-text.js');+const {+ BAR_BY_LOCATION, UNSUPPORTED_BAR, ROW_VERSION, ROW_SELECT, REASONS, CommandStateError, guidOf, normalizeCommandStates, SPEC_FLAG, serviceAnswerText,+} = require('./command-state-contract.js');++const CONTEXT_UNVERIFIED = 'command-state-context-unverified';+const ROW_UNREADABLE = 'command-state-row-unreadable';+const VERSION_UNAVAILABLE = 'command-state-version-unavailable';+// The platform's "does not exist" for a record: { "error": { "code": "0x80040217", "message": "appaction With Id = ... Does Not Exist" } }+// Only a 404 that carries it proves a row is gone; any other 404 (a wrong path, a proxy) proves nothing.+const NOT_FOUND = '0x80040217';++const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);+const has = (row, key) => Object.prototype.hasOwnProperty.call(row, key);++// The `code` of a Dataverse error answer — { "error": { "code": "0x80040217" } }, spelled `Error` by some surfaces — in lower case. It is+// compared, never said: what is said of an answer is serviceAnswerText's (lib/command-state-contract.js), which checks the code's shape.+function errorCode(body) {+ const envelope = isObject(body) ? (body.error || body.Error) : null;+ return isObject(envelope) && typeof envelope.code === 'string' ? envelope.code.toLowerCase() : '';+}++// What this feature says of a read that was refused or got no answer: its status and Dataverse error code, or, with no answer at all, the+// system error code (ECONNRESET) — serviceAnswerText, never the service's own text. The shared reader (collectionRows, lib/app-components.js)+// copies the service's `message` and the URL it read into the error it throws; it is left as it is, so a build without `commandStates` prints+// what it always printed, and this feature reads the facts from the answer instead (watched, below).+const failureOf = (answer) => ({ status: answer && answer.status, dataverseCode: errorCode(answer && answer.body) });+// An error this feature did not word, said by its status and system code; one of its own (a CommandStateError) keeps its words, which are+// serviceAnswerText's or fixed text.+function readFailureText(error) {+ if (error instanceof CommandStateError) return error.message;+ return serviceAnswerText({ status: error && error.statusCode, systemCode: error && error.code });+}++// The shared reader's complaints about an answer it WAS given (a 2xx), e.g.+// "the modern commands of table 'contoso_ticket': repeated @odata.nextLink"+// "the component list holds 1 row it cannot place: row 1 has an objectid that is no GUID ("<up to 40 characters of the service's value>")"+// read as the problem they name and the field they name, never copied: the second one quotes the service's value. A complaint not listed+// here is said as `unexpected`.+const SHARED_COMPLAINTS = [+ [/: repeated @odata\.nextLink$/, { problem: 'repeated-link' }],+ [/: malformed @odata\.nextLink$/, { problem: 'malformed-link', field: '@odata.nextLink' }],+ [/no readable result set$/, { problem: 'not-a-list', field: 'value' }],+ [/it cannot place: row \d+ is not a record/, { problem: 'not-a-record' }],+ [/it cannot place: row \d+ has (no objectid|an objectid that is no GUID)/, { problem: 'unplaceable', field: 'objectid' }],+ [/it cannot place: row \d+ (says no component type|has component type)/, { problem: 'unplaceable', field: 'componenttype' }],+ [/could not be resolved to a MetadataId \+ EntitySetName$/, { problem: 'malformed-field', field: ['MetadataId', 'EntitySetName'] }],+ [/^no single current layer among \d+ app row\(s\)$/, { problem: 'layer-ambiguous' }],+ // The transport's own refusal of a continuation, which currentAppLayer turns into a reason like any other error.+ [/^command-state transport: the next-page link pointed outside the expected API and was not followed$/, { problem: 'link-outside' }],+];+function complaintOf(text) {+ const found = SHARED_COMPLAINTS.find(([pattern]) => pattern.test(String(text)));+ return found ? found[1] : { problem: 'unexpected' };+}++// The reader, watched: the last read that was refused or got no answer, so a failure is said from its status and code rather than from the+// message the shared reader made of the service's text. Everything else is the reader's own (`apiUrl` and the rest, by prototype).+function watched(reader) {+ const watch = Object.create(reader);+ watch.failure = null;+ const seen = (answer) => {+ if (!answer || !(answer.status >= 200 && answer.status < 300)) watch.failure = failureOf(answer);+ return answer;+ };+ const thrown = (error) => {+ if (!(error instanceof CommandStateError)) watch.failure = { status: error && error.statusCode, systemCode: error && error.code };+ throw error;+ };+ for (const method of ['get', 'getAbsolute']) {+ // The transport is frozen, so its methods are read-only on the prototype and are shadowed by definition, not assignment.+ if (typeof reader[method] === 'function') {+ Object.defineProperty(watch, method, { value: (...args) => Promise.resolve().then(() => reader[method](...args)).then(seen, thrown) });+ }+ }+ return watch;+}++// Runs a read whose failure must carry this feature's code; a CommandStateError (the transport's refusal of a continuation) keeps its own.+// `run` is given the reader, watched. Every other failure is said as `<what>: <serviceAnswerText>`: a read that was refused or got no answer+// by its status and codes, a complaint about an answer that came by the problem it names (complaintOf).+async function as(code, what, reader, run) {+ const watch = watched(reader);+ try {+ return await run(watch);+ } catch (error) {+ if (error instanceof CommandStateError) throw error;+ const failure = watch.failure || (error && Number.isInteger(error.statusCode) ? { status: error.statusCode } : null);+ throw new CommandStateError(code, `${what}: ${serviceAnswerText(failure || complaintOf(error && error.message))}`);+ }+}++/**+ * Who the app is, which tables it holds, and whether the table of commands keeps row versions — everything a row is judged against.+ * 1. GET /appmodules?$select=appmoduleid,uniquename&$filter=uniquename eq '<name>' every page; exactly one app+ * 2. its current saved layer (currentAppLayer) one layer, never both unioned+ * 3. GET /appmodulecomponents?...componenttype eq 1 (appComponentRows, strict) the complete list of its tables+ * 4. the tables: each named one by logical name (tableRefs), or, when none is named, each table component by its metadata id+ * 5. GET /EntityDefinitions(LogicalName='appaction')?$select=IsOptimisticConcurrencyEnabled+ * @param {object} reader - lib/command-state-transport.js+ * @param {{ appUniqueName: string, entities?: string[] }} args - no entities: every table of the app+ * @returns {Promise<{ appId: string, appUniqueName: string, appModuleIdUnique: string, optimisticConcurrency: boolean,+ * tables: Map<string, { entity: string, metadataId: string, inApp: boolean }> }>}+ */+async function resolveCommandStateContext(reader, { appUniqueName, entities } = {}) {+ if (typeof appUniqueName !== 'string' || !appUniqueName.trim()) throw new CommandStateError(CONTEXT_UNVERIFIED, 'an app unique name is required');+ const apps = await as(CONTEXT_UNVERIFIED, `app '${appUniqueName}'`, reader, (r) => collectionRows(r,+ `/appmodules?$select=appmoduleid,uniquename&$filter=uniquename eq '${odataLit(appUniqueName)}'`, `app '${appUniqueName}'`, { code: CONTEXT_UNVERIFIED }));+ const appIds = apps.map((row) => (isObject(row) ? guidOf(row.appmoduleid) : null));+ if (appIds.some((id) => !id)) throw new CommandStateError(CONTEXT_UNVERIFIED, `app '${appUniqueName}': a row has no readable app id`);+ if (apps.length !== 1) {+ throw new CommandStateError(CONTEXT_UNVERIFIED, apps.length+ ? `app '${appUniqueName}': ${apps.length} published apps answer to this unique name`+ : `app '${appUniqueName}': no published app has this unique name`);+ }+ const appId = appIds[0];+ // currentAppLayer answers a failed read with the shared reader's message (layer.reason), which can quote the service: the watched reader says+ // a refused read from its status and code, and any other reason is read as the problem it names (complaintOf), never copied.+ const layerReader = watched(reader);+ const layer = await currentAppLayer(layerReader, appId);+ if (!layer.ok) {+ const failure = layerReader.failure || (Number.isInteger(layer.status) ? { status: layer.status } : complaintOf(layer.reason));+ throw new CommandStateError(CONTEXT_UNVERIFIED, `app '${appUniqueName}': its current layer could not be read: ${serviceAnswerText(failure)}`);+ }+ const components = await as(CONTEXT_UNVERIFIED, `app '${appUniqueName}': its tables`, reader, (r) => appComponentRows(r, layer.appModuleIdUnique, 1, { strict: true }));+ const memberIds = new Set(components.map((row) => guidOf(row.objectid)));++ const tables = new Map();+ if (Array.isArray(entities) && entities.length) {+ const names = [...new Set(entities.map((name) => String(name).toLowerCase()))];+ for (const name of names) {+ if (!TABLE_NAME.test(name)) throw new CommandStateError(CONTEXT_UNVERIFIED, `'${name}' is not a table's logical name`);+ }+ const refs = await as(CONTEXT_UNVERIFIED, `the tables ${names.join(', ')}`, reader, (r) => tableRefs(r, names));+ for (const name of names.sort(compareText)) {+ const { metadataId } = refs.get(name);+ tables.set(name, { entity: name, metadataId, inApp: memberIds.has(metadataId) });+ }+ } else {+ for (const metadataId of [...memberIds].sort()) {+ const what = `app '${appUniqueName}': table component ${metadataId}`;+ const answer = await as(CONTEXT_UNVERIFIED, what, reader, (r) => r.get(`/EntityDefinitions(${metadataId})?$select=LogicalName,MetadataId`));+ const answered = answer && answer.status >= 200 && answer.status < 300;+ const body = answered ? answer.body : undefined;+ let problem = null;+ if (!answered) problem = failureOf(answer);+ else if (!isObject(body)) problem = { problem: 'not-a-record' };+ else if (typeof body.LogicalName !== 'string' || !TABLE_NAME.test(body.LogicalName)) problem = { problem: 'malformed-field', field: 'LogicalName' };+ else if (guidOf(body.MetadataId) !== metadataId) problem = { problem: 'malformed-field', field: 'MetadataId' };+ if (problem) throw new CommandStateError(CONTEXT_UNVERIFIED, `${what} could not be resolved to a table: ${serviceAnswerText(problem)}`);+ tables.set(body.LogicalName, { entity: body.LogicalName, metadataId, inApp: true });+ }+ }++ // A row version exists only where the table keeps one: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/perform-conditional-operations-using-web-api+ // Missing, not a boolean, or unreadable is no answer, never "on".+ const concurrency = await as(VERSION_UNAVAILABLE, 'whether the command table keeps row versions', reader, (r) => r.get("/EntityDefinitions(LogicalName='appaction')?$select=IsOptimisticConcurrencyEnabled"));+ const answered = concurrency && concurrency.status >= 200 && concurrency.status < 300;+ const flag = answered && isObject(concurrency.body) ? concurrency.body.IsOptimisticConcurrencyEnabled : undefined;+ if (typeof flag !== 'boolean') {+ const problem = answered ? { problem: 'malformed-field', field: 'IsOptimisticConcurrencyEnabled' } : failureOf(concurrency);+ throw new CommandStateError(VERSION_UNAVAILABLE, `whether the command table keeps row versions could not be read: ${serviceAnswerText(problem)}`);+ }+ return {+ appId, appUniqueName, appModuleIdUnique: layer.appModuleIdUnique, optimisticConcurrency: flag,+ tables: new Map([...tables].sort(([a], [b]) => compareText(a, b))),+ };+}++/**+ * One row, by its id:+ * GET /appactions(<rowId>)?$select=<ROW_SELECT>+ * @returns {Promise<{ found: true, body: object } | { found: false }>} not found only for a 404 with the platform's "does not exist" code+ */+async function readCommandStateRow(reader, rowId) {+ const id = guidOf(rowId);+ if (!id || id !== rowId) throw new CommandStateError(ROW_UNREADABLE, `'${rowId}' is not a row id`);+ let answer;+ try {+ answer = await reader.get(`/appactions(${id})?$select=${ROW_SELECT.join(',')}`);+ } catch (error) {+ if (error instanceof CommandStateError) throw error;+ throw new CommandStateError(ROW_UNREADABLE, `command row ${id} could not be read: ${readFailureText(error)}`);+ }+ const status = answer && answer.status;+ if (status === 404 && errorCode(answer.body) === NOT_FOUND) return { found: false };+ if (!(status >= 200 && status < 300)) {+ throw new CommandStateError(ROW_UNREADABLE, `command row ${id} could not be read: ${serviceAnswerText(failureOf(answer))}`);+ }+ if (!isObject(answer.body)) throw new CommandStateError(ROW_UNREADABLE, `command row ${id} could not be read: ${serviceAnswerText({ problem: 'not-a-record' })}`);+ return { found: true, body: answer.body };+}++/**+ * What a row is, and every reason it is not a candidate for a row-state edit — none means it is one. Every column of ROW_SELECT must be in the+ * answer, of its kind: a missing column, a number spelled as text and a null where a number or a true/false belongs are each `shape-unreadable`+ * (or `flags-unreadable` for the two flags), never a default. `details` name the columns, never a value the platform sent.+ * @param {object} body - the row as the platform answered it+ * @param {object} expect+ * @param {string} [expect.rowId] the row asked for+ * @param {string} [expect.entity] the table's logical name+ * @param {string} [expect.metadataId] the table's metadata id+ * @param {string} [expect.appId] the app+ * @param {boolean} [expect.inApp] false: the table is not one of the app's+ * @param {number} [expect.location] the declared bar's number+ * @param {boolean} [expect.optimisticConcurrency] false: the table of commands keeps no row versions+ * @param {boolean} [expect.requireVersion] the answer must carry a usable row version+ */+function decodeCommandStateRow(body, expect = {}) {+ if (!isObject(body)) throw new CommandStateError(ROW_UNREADABLE, 'a command row is not a record');+ const reasons = new Set();+ const details = [];+ const bad = (field, why) => { reasons.add('shape-unreadable'); details.push(`${field} ${why}`); };+ for (const key of ROW_SELECT) if (!has(body, key)) bad(key, 'is missing');+ const int = (key) => {+ if (!has(body, key)) return null;+ if (Number.isInteger(body[key])) return body[key];+ bad(key, 'is not a whole number');+ return null;+ };+ const text = (key) => {+ if (!has(body, key) || body[key] === null) return null;+ if (typeof body[key] === 'string') return body[key];+ bad(key, 'is not text');+ return null;+ };+ // A lookup's value: null, or a GUID.+ const ref = (key) => {+ if (!has(body, key) || body[key] === null) return null;+ const id = guidOf(body[key]);+ if (!id) bad(key, 'is not a GUID');+ return id;+ };++ const rowId = guidOf(body.appactionid);+ if (has(body, 'appactionid') && !rowId) bad('appactionid', 'is not a GUID');+ if (expect.rowId && rowId && rowId !== expect.rowId) reasons.add('id-mismatch');++ const caption = text('buttonlabeltext');+ const name = text('name');+ const uniqueName = text('uniquename');++ const context = int('context');+ if (context !== null && context !== 1) reasons.add('context-not-table');+ const contextValue = text('contextvalue');+ const entity = contextValue === null ? null : contextValue.toLowerCase();+ const contextEntity = ref('_contextentity_value');+ if (expect.entity !== undefined && entity !== expect.entity) reasons.add('context-mismatch');+ if (expect.metadataId !== undefined && has(body, '_contextentity_value') && contextEntity !== expect.metadataId) reasons.add('context-mismatch');+ if (expect.inApp === false) reasons.add('table-not-in-app');++ const location = int('location');+ const bar = location !== null && has(BAR_BY_LOCATION, location) ? BAR_BY_LOCATION[location] : UNSUPPORTED_BAR;+ if (location !== null && bar === UNSUPPORTED_BAR) reasons.add('location-unsupported');+ if (expect.location !== undefined && location !== null && location !== expect.location) reasons.add('location-mismatch');++ // Only a table-scoped row (`_appmoduleid_value` present and null) is a candidate. A row scoped to an app — this app's own included — is not:+ // how an app-scoped row and its table-scoped siblings render together has not been measured, so it is refused, never widened to a broader edit.+ const owner = ref('_appmoduleid_value');+ let scope = 'unknown';+ if (has(body, '_appmoduleid_value')) {+ if (body._appmoduleid_value === null) scope = 'table';+ else if (owner && expect.appId !== undefined) scope = owner === expect.appId ? 'app' : 'other-app';+ else if (owner) scope = 'app';+ }+ if (scope === 'app' || scope === 'other-app') reasons.add('app-scoped');++ const type = int('type');+ if (type !== null && type !== 0) reasons.add('not-standard-button');+ const parentId = ref('_parentappactionid_value');+ if (parentId) reasons.add('nested');+ const origin = int('origin');+ if (origin !== null && origin !== 0) reasons.add('not-default-origin');+ const statecode = int('statecode');+ const statuscode = int('statuscode');+ if (statecode !== null && statuscode !== null && !(statecode === 0 && statuscode === 1)) reasons.add('inactive');++ let managed = null;+ if (has(body, 'ismanaged')) {+ if (typeof body.ismanaged === 'boolean') managed = body.ismanaged;+ else bad('ismanaged', 'is not true or false');+ }+ if (managed === true) reasons.add('managed');+ // A managed property is { "Value": true, "CanBeChanged": ..., "ManagedPropertyLogicalName": ... }; only Value says what it is.+ let customizable = null;+ if (has(body, 'iscustomizable')) {+ if (isObject(body.iscustomizable) && typeof body.iscustomizable.Value === 'boolean') customizable = body.iscustomizable.Value;+ else bad('iscustomizable', 'is not a managed property with a true or false Value');+ }+ if (customizable === false) reasons.add('not-customizable');++ const flag = (key) => {+ if (has(body, key) && typeof body[key] === 'boolean') return body[key];+ reasons.add('flags-unreadable');+ if (has(body, key)) details.push(`${key} is not true or false`);+ return null;+ };+ const hidden = flag('hidden');+ const disabled = flag('isdisabled');++ // Static visibility is `visibilitytype` PRESENT and null or 0, with every formula column present and null or empty. Null is what the+ // platform stores on the buttons a plain `commands[]` build writes (measured: every such row), so it is accepted here — but only as a+ // present null: a missing column stays unreadable, and 1 (Power Fx), 2 (classic rules), -1 or a number spelled as text never pass.+ // The feature never writes `visibilitytype`, not even to turn this null into 0.+ let visibilityType = null;+ if (has(body, 'visibilitytype') && body.visibilitytype !== null) {+ visibilityType = int('visibilitytype');+ if (visibilityType !== null && visibilityType !== 0) reasons.add('visibility-formula');+ }+ const formulaLibraryId = body._visibilityformulacomponentlibraryid_value === '' ? null : ref('_visibilityformulacomponentlibraryid_value');+ if (formulaLibraryId) reasons.add('visibility-formula');+ for (const key of ['visibilityformulacomponentlibrary', 'visibilityformulacomponentname', 'visibilityformulafunctionname']) {+ const value = text(key);+ if (value !== null && value !== '') reasons.add('visibility-formula');+ }+ const onClickType = int('onclickeventtype');+ if (onClickType === 1) reasons.add('formula-action');+ else if (onClickType !== null && onClickType !== 0 && onClickType !== 2) bad('onclickeventtype', 'is not a known kind of action');++ const etag = body['@odata.etag'];+ const version = typeof etag === 'string' && ROW_VERSION.test(etag) ? etag : null;+ if (expect.optimisticConcurrency === false) reasons.add('version-unavailable');+ if (expect.requireVersion && !version) reasons.add('version-unavailable');++ const ordered = REASONS.filter((reason) => reasons.has(reason));+ return {+ eligible: ordered.length === 0,+ reasons: ordered,+ details,+ row: {+ rowId, entity, contextEntityId: contextEntity, location, bar, caption, name, uniqueName, scope, appId: owner,+ type, origin, parentId, statecode, statuscode, managed, customizable, hidden, disabled, visibilityType, onClickType, version,+ },+ };+}++const captionKey = (caption) => (typeof caption === 'string' ? caption.trim().toLowerCase() : null);++/**+ * Every modern command bound to each table of the context, decoded, with why it is or is not a candidate. A row the platform answers more than+ * once, or an answer that is not a record, makes the whole read fail: the list must be complete to say "this is every button".+ * GET /appactions?$select=<ROW_SELECT>&$filter=contextvalue eq '<table>' every page, per table+ * `contextvalue` is the column download-model-app.js's command inventory and the teardown read a table's commands by.+ * @param {object} reader+ * @param {Awaited<ReturnType<typeof resolveCommandStateContext>>} context+ * @param {{ location?: number }} [filter] - keep the rows of one bar+ * @returns {Promise<object[]>} sorted by table, bar number, caption (unlabelled last), row id+ */+async function listCommandStateRows(reader, context, { location } = {}) {+ const out = [];+ const seen = new Set();+ for (const table of context.tables.values()) {+ const rows = await as(ROW_UNREADABLE, `the modern commands of table '${table.entity}'`, reader, (r) => collectionRows(r,+ `/appactions?$select=${ROW_SELECT.join(',')}&$filter=contextvalue eq '${odataLit(table.entity)}'`,+ `the modern commands of table '${table.entity}'`, { code: ROW_UNREADABLE }));+ for (const body of rows) {+ if (!isObject(body)) throw new CommandStateError(ROW_UNREADABLE, `the modern commands of table '${table.entity}': an answer row is not a record`);+ const decoded = decodeCommandStateRow(body, {+ entity: table.entity, metadataId: table.metadataId, appId: context.appId, inApp: table.inApp, optimisticConcurrency: context.optimisticConcurrency,+ });+ const id = decoded.row.rowId;+ if (id) {+ if (seen.has(id)) throw new CommandStateError(ROW_UNREADABLE, `the modern commands of table '${table.entity}': row ${id} was answered twice`);+ seen.add(id);+ }+ if (location !== undefined && decoded.row.location !== location) continue;+ out.push({ table: table.entity, ...decoded });+ }+ }+ // Two buttons with the same caption on one bar of one table are each named by their row id, and neither is picked for the other.+ const byCaption = new Map();+ for (const item of out) {+ const key = captionKey(item.row.caption);+ if (key === null) continue;+ const group = `${item.table}\u0000${item.row.location}\u0000${key}`;+ if (!byCaption.has(group)) byCaption.set(group, []);+ byCaption.get(group).push(item);+ }+ for (const group of byCaption.values()) {+ if (group.length < 2) continue;+ for (const item of group) item.sameCaption = group.filter((other) => other !== item).map((other) => other.row.rowId);+ }+ const nullLast = (a, b, compare) => (a === null ? (b === null ? 0 : 1) : b === null ? -1 : compare(a, b));+ out.sort((a, b) => compareText(a.table, b.table)+ || nullLast(a.row.location, b.row.location, (x, y) => x - y)+ || nullLast(a.row.caption, b.row.caption, compareText)+ || nullLast(a.row.rowId, b.row.rowId, compareText));+ return out;+}++// The reasons that say a row is not the one declared, or cannot be read as it — each fails the check. The others (managed, a formula, no row+// version, ...) say only that a build would refuse to write the row; they do not change what its stored flags are.+const NOT_THE_DECLARED_ROW = new Set([+ 'shape-unreadable', 'flags-unreadable', 'id-mismatch', 'context-not-table', 'context-mismatch', 'table-not-in-app',+ 'location-unsupported', 'location-mismatch', 'app-scoped',+]);+const STORED_ONLY = 'stored flags of the exact row; how the button renders is not checked';++/**+ * Whether each declared `commandStates[]` entry holds in the environment: its row exists, is the table-scoped row of the declared table and bar+ * in this app, and stores every flag the entry declares. A flag the entry leaves out is not checked. Read only: no approval is needed.+ * Anything that cannot be read fails the entry's check — never a pass, never left out.+ * @param {object} reader - lib/command-state-transport.js+ * @param {object} spec+ * @returns {Promise<Array<{ name: string, present: boolean, detail: string }>>} one per declared entry, in spec order+ */+async function verifyCommandStates(reader, spec) {+ const states = normalizeCommandStates(spec);+ if (!states.length) return [];+ const nameOf = (s) => `${s.entity} ${s.bar} row ${s.rowId}`;+ let context;+ try {+ context = await resolveCommandStateContext(reader, {+ appUniqueName: spec && spec.app && spec.app.uniqueName, entities: [...new Set(states.map((s) => s.entity))],+ });+ } catch (error) {+ return states.map((s) => ({ name: nameOf(s), present: false, detail: `could not be read: ${readFailureText(error)}` }));+ }+ const out = [];+ for (const s of states) {+ let failure = null;+ let flags = '';+ try {+ const read = await readCommandStateRow(reader, s.rowId);+ if (!read.found) {+ failure = 'the row does not exist';+ } else {+ const table = context.tables.get(s.entity);+ const decoded = decodeCommandStateRow(read.body, {+ rowId: s.rowId, entity: s.entity, metadataId: table.metadataId, appId: context.appId, inApp: table.inApp, location: s.location,+ });+ const wrong = decoded.reasons.filter((reason) => NOT_THE_DECLARED_ROW.has(reason));+ if (wrong.length) {+ failure = `not the declared row: ${wrong.join(', ')}${decoded.details.length ? ` (${decoded.details.join('; ')})` : ''}`;+ } else {+ // `desired` is by column name (hidden, isdisabled); the decoded row and the spec say `disabled`.+ const stored = (wire) => decoded.row[SPEC_FLAG[wire]];+ const differ = Object.keys(s.desired).filter((wire) => stored(wire) !== s.desired[wire]);+ flags = Object.keys(s.desired).map((wire) => `${SPEC_FLAG[wire]} ${stored(wire)}`).join(', ');+ if (differ.length) failure = differ.map((wire) => `${SPEC_FLAG[wire]} is ${stored(wire)}, declared ${s.desired[wire]}`).join('; ');+ }+ }+ } catch (error) {+ failure = `could not be read: ${readFailureText(error)}`;+ }+ out.push({ name: nameOf(s), present: !failure, detail: failure ? `${failure} (${STORED_ONLY})` : `${flags} (${STORED_ONLY})` });+ }+ return out;+}++module.exports = {+ resolveCommandStateContext, readCommandStateRow, decodeCommandStateRow, listCommandStateRows, verifyCommandStates, errorCode, NOT_FOUND,+ readFailureText,+};diff --git a/plugins/model-apps/scripts/lib/command-state-run.js b/plugins/model-apps/scripts/lib/command-state-run.jsnew file mode 100644index 000000000..bf76b5872--- /dev/null+++ b/plugins/model-apps/scripts/lib/command-state-run.js@@ -0,0 +1,869 @@+'use strict';+// The build's side of `commandStates[]`: set the hidden / disabled state of existing table-scoped modern command rows, by row id, and see+// that the build's own table publication covered each table it wrote on. Created per build attempt (createCommandStateRun); the publication+// observer (createCommandStatePublicationObserver) lives for the whole invocation, across the build's own retries. In memory only: nothing+// here is persisted, and nothing here sends a publish — the build's existing before-app table publication does that, and the observer only+// records what it answered.+//+// Order within one attempt (lib/sdk-build.js):+// preflight() before the build's first write: every row read and judged, every approval present — or the build stops having written nothing+// recheckAll() in the commands phase: everything read again; a row that changed since its approval stops the build (approval-stale)+// applyRows() then, one row at a time: a fresh read, one conditional PATCH of the flags that differ, a read back; then every row read again+// assertComplete() after all the build's shared work: every declared table's publication confirmed for its latest write, or exit 1+//+// Every refusal and every unknown outcome is a BuildHalt that is never retried automatically (RETRY.NEVER): a run again re-reads the row and+// asks for approval of what it then finds; it never replays a write.++const {+ usesCommandStates, normalizeCommandStates, diffCommandFlags, commandStateApprovalKey, commandTablePublishApprovalKey, codeForReasons, canonicalOrigin,+ CommandStateError, SPEC_FLAG, validateCommandStates, serviceAnswerText,+} = require('./command-state-contract.js');+const { resolveCommandStateContext, readCommandStateRow, decodeCommandStateRow, errorCode, NOT_FOUND, readFailureText } = require('./command-state-read.js');+const { PHASES, STAGES } = require('./stages.js');++const CODES = Object.freeze({+ transport: 'command-state-transport-unavailable',+ publishRequired: 'command-state-publish-required',+ phaseUnsupported: 'command-state-phase-unsupported',+ keyedUnsupported: 'command-state-keyed-unsupported',+ legacyCreateConflict: 'command-state-legacy-create-conflict',+ approvalRequired: 'command-state-approval-required',+ approvalStale: 'command-state-approval-stale',+ publicationApprovalRequired: 'command-state-publication-approval-required',+ rowNotFound: 'command-state-row-not-found',+ rowUnreadable: 'command-state-row-unreadable',+ versionUnavailable: 'command-state-version-unavailable',+ versionConflict: 'command-state-version-conflict',+ updateRejected: 'command-state-update-rejected',+ writeUnknown: 'command-state-write-unknown',+ notConfirmed: 'command-state-not-confirmed',+ publishUnconfirmed: 'command-state-publish-unconfirmed',+});++// What to do next, one fixed sentence per code: never a service's own words, which can quote a record value.+const REMEDY = Object.freeze({+ [CODES.transport]: 'this build has no way to read and write command rows; run it through build-model-app.js',+ [CODES.publishRequired]: 'run the build with --publish: a command state is applied only by a build that also publishes its table',+ [CODES.phaseUnsupported]: 'run a full build (or exactly --stage data, which leaves command states alone)',+ [CODES.keyedUnsupported]: 'a build cannot use commandStates together with keyed commands[] (key) yet: remove one of them',+ [CODES.legacyCreateConflict]: 'commands[] would create a new command bar on a table whose existing button commandStates edits: create the button in one build, then add its state in a later one',+ [CODES.approvalRequired]: 'review each change above and run the build again with every --authorize it printed',+ [CODES.approvalStale]: 'the row changed after it was approved: run a dry run to see what it holds now, and approve the new token',+ [CODES.publicationApprovalRequired]: 'run the build again with every --authorize publish:command-state-table:... it printed; it publishes ALL saved customizations on that table',+ [CODES.rowNotFound]: 'no such row in this environment: list the app\'s buttons with list-command-states.js and correct rowId (a row is never created)',+ [CODES.rowUnreadable]: 'the row could not be read, so nothing about it is assumed: check access and the environment, then run the build again',+ [CODES.versionUnavailable]: 'the row has no usable version to make a conditional write against, so it is not written',+ [CODES.versionConflict]: 'someone changed the row after it was read; nothing was overwritten. Run a dry run, review the row and approve its new token',+ [CODES.updateRejected]: 'the platform refused the write; nothing was changed by it. Check access to the row, then run the build again',+ [CODES.writeUnknown]: 'the write may still complete; nothing was sent again. Read the row (list-command-states.js) before running the build again',+ [CODES.notConfirmed]: 'the declared flags are not confirmed on the row. Read the row (list-command-states.js) before running the build again',+ [CODES.publishUnconfirmed]: 'run the build again with publishing',+ 'command-state-context-unverified': 'the app or its tables could not be confirmed: check app.uniqueName and that each table is in the app',+ 'command-state-target-mismatch': 'the row is not the declared table\'s button on the declared bar: list the app\'s buttons and correct the entry',+ 'command-state-target-unsupported': 'this kind of button is not edited in this version (only active, unmanaged, top-level plain buttons with no visibility formula are)',+ 'command-state-app-scope-unverified': 'app-scoped command rows are not edited in this version; only table-scoped rows are',+ 'command-state-spec-invalid': 'correct the commandStates entries named above (or leave commandStates out)',+});++// The approval display: each change and the exact token that approves it, e.g.+// commandStates — approve to apply (pass every --authorize back to the build):+// new_ticket MainTab button "Go" (row <rowId>, ...): hidden false -> true+// --authorize overwrite:command-state:new_ticket/MainTab/<rowId>/<sha256>+const approvalDisplayOf = (lines) => `commandStates — approve to apply (pass every --authorize back to the build):\n${lines.map(([what, token]) => ` ${what}\n --authorize ${token}`).join('\n')}`;++const sameSet = (a, b) => Array.isArray(a) && a.length === b.length && a.every((x, i) => x === b[i]);+const flagWords = (flags) => Object.entries(flags).map(([key, value]) => `${SPEC_FLAG[key]} ${value}`).join(', ');++/**+ * How a build treats the spec's command states:+ * off the feature is not used (absent or []): nothing below runs, nothing is read+ * plan a dry run: read-only planning when the commands phase is selected+ * data-stage exactly --stage data: command states are not applied, needs no approval, reads nothing+ * apply a full build with --publish+ * or an error: { code, message } for any other apply — refused before the build writes anything.+ */+function commandStateMode(spec, { apply = false, publish = false, phases = PHASES, changedOnlyFast = false } = {}) {+ if (!usesCommandStates(spec)) return { mode: 'off' };+ if (!apply) return { mode: 'plan' };+ if (!changedOnlyFast && sameSet(phases, STAGES.data)) return { mode: 'data-stage' };+ if (changedOnlyFast || !sameSet(phases, PHASES)) {+ return { mode: 'error', code: CODES.phaseUnsupported, message: `commandStates: a partial apply (${(phases || []).join(',')}) cannot apply command states. ${REMEDY[CODES.phaseUnsupported]}` };+ }+ if (!publish) return { mode: 'error', code: CODES.publishRequired, message: `commandStates: ${REMEDY[CODES.publishRequired]}.` };+ const keyed = (c) => !!(c && (c.key !== undefined || (Array.isArray(c.children) && c.children.some(keyed))));+ if ((Array.isArray(spec.commands) ? spec.commands : []).some(keyed)) {+ return { mode: 'error', code: CODES.keyedUnsupported, message: `commandStates: ${REMEDY[CODES.keyedUnsupported]}.` };+ }+ return { mode: 'apply' };+}++// The remedy of a row that no longer holds its flags at the final proof: no write of this build is claimed, and none is undone.+const LATE_MISMATCH_REMEDY = 'this build did not overwrite that change and rolls nothing back. Read the row (list-command-states.js), find out what changed it, then run the build again';++// Every outcome createCommandStateRun records for a row: `planned` before anything happens to it, then only what `record` accepts+// (checkRowRecord, which also checks the outcome against the row's facts below). The outcome is a short name for the row's step; it is never+// what a message says. Every message words the row from its FACTS, the ordered list of what the build read and sent for it:+// unchanged no write was sent and the last read found the declared flags+// acknowledged the last write was answered 200/204, and every read since it found the flags+// observed-matching-after-unknown-send the last write got no usable answer, and every read since it (at least one) found the flags+// unknown a write was sent and not every read since it found the flags+// refused no write was sent, or the last one was refused+// drifted one of the first three, then the read after every row's step did not find the flags; `before` keeps which one+const ROW_OUTCOMES = Object.freeze(['planned', 'unchanged', 'acknowledged', 'observed-matching-after-unknown-send', 'unknown', 'refused', 'drifted']);+// What a `drifted` row was before its later read: a row that matched after its own step.+const DRIFT_BEFORE = Object.freeze(['unchanged', 'acknowledged', 'observed-matching-after-unknown-send']);+// The one word for a write answered 200/204: a send's `answer` in the facts, and the outcome of a row read back holding its flags after one.+// It is named here, inside the vocabulary, so that no literal outside the vocabulary says it.+const ACKNOWLEDGED = 'acknowledged';+// The ONE vocabulary every claim about a row is made of (the renderer, renderRowHistory, and the publication kinds, rowKind, compose these and+// nothing else that claims a write). The rule the words keep: only a write answered 200/204 AND then read back holding the flags is+// "accepted" or "saved"; a write with no usable answer says its outcome is unknown and what a later read found; a row this build did not+// write says so; a read that could not be judged says only that.+const ROW_PHRASES = Object.freeze({+ notWritten: 'not written by this build',+ stoppedBefore: 'the build stopped before it',+ alreadyHeld: 'it already held the declared flags',+ writtenAndReadBack: 'written by this build: the write was accepted and read back holding the declared flags',+ answered: (status) => `this build's write was answered HTTP ${status}`,+ noAnswer: 'this build\'s write got no answer, so its outcome is unknown',+ noUsableAnswer: (status) => `this build's write got no usable answer (HTTP ${status}), so its outcome is unknown`,+ laterMatchAfterLost: 'a later read found the declared flags, which is not proof this build saved them',+ refusedSend: (status) => `its write was refused${status ? ` (HTTP ${status})` : ''}`,+ unnamed: 'what this build did to it is not known',+});+// Where in the build a read was made, as said after "a read".+const READ_PHASES = Object.freeze({+ plan: 'in the dry run',+ preflight: 'at the start of the build',+ recheck: 'in the commands phase, before the row writes',+ 'own-step': 'at its own step',+ readback: 'after its write',+ 'after-every-row': 'after every row\'s step',+ final: 'at the end of the build',+});+// A row's publication kind (rowKind), the words a table says when all its rows share it, and the order a mixed table counts them in.+const KINDS = Object.freeze({+ saved: 'saved',+ heldAfterLost: 'held after a write with no usable answer',+ alreadyHeld: 'already held',+ otherFlags: 'held other flags at its last read',+ unreadable: 'could not be read at its last read',+ unknown: 'outcome unknown',+ notWritten: 'not written',+});+const KIND_WHOLE = Object.freeze({+ [KINDS.saved]: 'saved, not published',+ [KINDS.heldAfterLost]: 'held the declared flags after a write with no usable answer (not known to be this build\'s), not published',+ [KINDS.alreadyHeld]: 'already held the declared flags, not published by this build',+ [KINDS.otherFlags]: 'held other flags than declared at its last read, not published',+ [KINDS.unreadable]: 'could not be read at its last read, not published',+ [KINDS.unknown]: 'write outcome unknown, not published',+ [KINDS.notWritten]: 'not written, not published',+});+const KIND_ORDER = Object.freeze(Object.values(KINDS));+const named = (outcome) => typeof outcome === 'string' && ROW_OUTCOMES.includes(outcome);++// The facts of one row, in order: what each read found and how each write was answered. They hold no version, token or service text.+// { attempt, kind: 'read', phase: <READ_PHASES key>, result: 'matched' | 'differed' | 'unreadable', hidden?, disabled?, code? }+// { attempt, kind: 'send', answer: 'acknowledged' | 'lost' | 'refused', status?, flags }+// `lost` is a send whose answer does not say whether it landed (none, 5xx, 408, 429 or a status this does not expect).+const isRead = (e) => !!e && e.kind === 'read';+const isSend = (e) => !!e && e.kind === 'send';+const counts = (e) => isSend(e) && (e.answer === ACKNOWLEDGED || e.answer === 'lost');+const matched = (e) => e.result === 'matched';+// The last write that may have landed, and the reads made after it (every read, when there is none).+function sinceLastSend(facts) {+ let at = -1;+ facts.forEach((e, i) => { if (counts(e)) at = i; });+ return { send: at >= 0 ? facts[at] : null, reads: facts.slice(at + 1).filter(isRead) };+}++// Consecutive reads of one attempt that found the same thing, as one.+function readRuns(reads) {+ const runs = [];+ for (const e of reads) {+ const key = `${e.attempt}|${e.result}|${e.hidden}|${e.disabled}|${e.code}`;+ if (runs.length && runs[runs.length - 1].key === key) continue;+ runs.push({ key, first: e });+ }+ return runs;+}+const readClause = (e) => {+ const where = READ_PHASES[e.phase] || 'at a step of the build';+ if (e.result === 'matched') return `a read ${where} found the declared flags`;+ if (e.result === 'differed') return `a read ${where} found hidden ${e.hidden}, disabled ${e.disabled}, not the declared flags`;+ return `the row could not be read and judged ${where} (${e.code || 'read failed'})`;+};++/**+ * What this build did to a row and what its reads found, from its facts alone: the one renderer every message after a row's step uses. A row+ * whose facts span more than one attempt of the build tags each clause with its attempt.+ */+function renderRowHistory(facts) {+ if (!Array.isArray(facts)) return ROW_PHRASES.unnamed;+ const multi = new Set(facts.map((e) => e.attempt)).size > 1;+ const tag = (e) => (multi ? ` (attempt ${e.attempt})` : '');+ const sends = facts.map((e, i) => [e, i]).filter(([e]) => isSend(e));+ if (!sends.length) {+ const runs = readRuns(facts.filter(isRead));+ if (!runs.length) return `${ROW_PHRASES.notWritten} (${ROW_PHRASES.stoppedBefore})`;+ const [first, ...rest] = runs;+ return [`${ROW_PHRASES.notWritten} (${matched(first.first) ? ROW_PHRASES.alreadyHeld : readClause(first.first)})${tag(first.first)}`,+ ...rest.map((r) => `then ${readClause(r.first)}${tag(r.first)}`)].join('; ');+ }+ // What the row held before a write is why it was written, which its approval said; the history starts at the first write.+ const clauses = [];+ sends.forEach(([send, at], n) => {+ const end = n + 1 < sends.length ? sends[n + 1][1] : facts.length;+ let runs = readRuns(facts.slice(at + 1, end).filter(isRead));+ if (send.answer === ACKNOWLEDGED) {+ if (runs.length && matched(runs[0].first) && runs[0].first.phase === 'readback' && runs[0].first.attempt === send.attempt) {+ clauses.push(`${ROW_PHRASES.writtenAndReadBack}${tag(send)}`);+ runs = runs.slice(1);+ } else {+ clauses.push(`${ROW_PHRASES.answered(send.status)}${tag(send)}`);+ }+ } else if (send.answer === 'lost') {+ clauses.push(`${Number.isInteger(send.status) ? ROW_PHRASES.noUsableAnswer(send.status) : ROW_PHRASES.noAnswer}${tag(send)}`);+ if (runs.length && matched(runs[0].first)) {+ clauses.push(`${ROW_PHRASES.laterMatchAfterLost}${tag(runs[0].first)}`);+ runs = runs.slice(1);+ }+ } else {+ clauses.push(`${ROW_PHRASES.notWritten}: ${ROW_PHRASES.refusedSend(send.status)}${tag(send)}`);+ }+ for (const r of runs) clauses.push(`then ${readClause(r.first)}${tag(r.first)}`);+ });+ return clauses.join('; ');+}++/** A row's publication kind (KIND_WHOLE), from its facts alone: its last read, and the last write that may have landed. */+function rowKind(facts) {+ if (!Array.isArray(facts)) return KINDS.unknown;+ const reads = facts.filter(isRead);+ const { send, reads: after } = sinceLastSend(facts);+ const last = reads[reads.length - 1];+ const lostAfterMatch = (list) => {+ const end = list[list.length - 1];+ if (!end || matched(end) || !list.some(matched)) return null;+ return end.result === 'differed' ? KINDS.otherFlags : KINDS.unreadable;+ };+ if (!send) {+ if (!last) return KINDS.notWritten;+ if (matched(last)) return KINDS.alreadyHeld;+ return lostAfterMatch(reads) || KINDS.notWritten;+ }+ if (after.length && after.every(matched)) return send.answer === ACKNOWLEDGED ? KINDS.saved : KINDS.heldAfterLost;+ return lostAfterMatch(after) || KINDS.unknown;+}++// Whether `outcome` is what the facts show (see ROW_OUTCOMES): the outcome a row is recorded with can never say more than its facts.+function factsShow(outcome, before, facts) {+ const reads = facts.filter(isRead);+ const last = reads[reads.length - 1];+ const { send, reads: after } = sinceLastSend(facts);+ const allMatched = after.length > 0 && after.every(matched);+ const lastSendOfAny = [...facts].reverse().find(isSend);+ switch (outcome) {+ case 'unchanged': return !send && !!last && matched(last);+ case ACKNOWLEDGED: return !!send && send.answer === ACKNOWLEDGED && allMatched;+ case 'observed-matching-after-unknown-send': return !!send && send.answer === 'lost' && allMatched;+ case 'unknown': return !!send && !allMatched;+ case 'refused': return !send || (!!lastSendOfAny && lastSendOfAny.answer === 'refused');+ case 'drifted': {+ if (!last || matched(last)) return false;+ let end = facts.length;+ while (end > 0 && isRead(facts[end - 1]) && !matched(facts[end - 1])) end -= 1;+ return factsShow(before, undefined, facts.slice(0, end));+ }+ default: return false;+ }+}++const rowHistory = (row) => (row && Array.isArray(row.facts) ? renderRowHistory(row.facts) : ROW_PHRASES.unnamed);+const rowLabel = (r) => `command state ${r.entity}/${r.location}/${r.rowId}`;+const ROW_MESSAGES = Object.freeze({+ /** A publication-unconfirmed table, from the facts of its rows. */+ publicationTable(entity, rows) {+ if (!rows.length) return `${entity}: publication not confirmed`;+ const tally = new Map();+ for (const r of rows) { const kind = rowKind(r && r.facts); tally.set(kind, (tally.get(kind) || 0) + 1); }+ if (tally.size === 1) return `${entity}: ${KIND_WHOLE[[...tally.keys()][0]]}`;+ return `${entity}: ${rows.length} rows (${KIND_ORDER.filter((k) => tally.has(k)).map((k) => `${tally.get(k)} ${k}`).join(', ')}), not published`;+ },+ /** A row whose read after every row's step did not find the declared flags. */+ postWriteMismatch(row) {+ return `${rowLabel(row)}: ${rowHistory(row)}`;+ },+ /** The final proof's preface: what this build did to every declared row, none of which is rolled back. */+ lateNote(rows) {+ return `checked again at the end of the build, after its app work; nothing is rolled back (${rows.map((r) => `${rowLabel(r)}: ${rowHistory(r)}`).join('; ')})`;+ },+ /** A row that no longer holds its declared flags at the final proof (its facts end with that read). */+ finalDrift(row) {+ return `${rowLabel(row)}: ${rowHistory(row)} — ${LATE_MISMATCH_REMEDY}`;+ },+ /** A row's line in the result an apply (or its halt) prints. */+ resultLine(row) {+ return `${rowLabel(row)}: ${row.outcome}${row.before ? ` after ${row.before}` : ''}${row.changed && row.changed.length ? ` (${row.changed.join(', ')})` : ''}${row.code ? ` [${row.code}]` : ''} — ${rowHistory(row)}`;+ },+});++/**+ * The one boundary a row's outcome is recorded through (createCommandStateRun's `record`): an outcome ROW_OUTCOMES does not name, `planned`+ * (only ever the starting value), a `drifted` without the matching history it came from, a `before` on any other outcome, or — given the+ * row's facts — an outcome its facts do not show is a defect in this module, thrown as one: never recorded. Without facts it checks the+ * vocabulary only.+ */+function checkRowRecord(patch, facts) {+ const outcome = patch && patch.outcome;+ if (!named(outcome) || outcome === 'planned') throw new TypeError(`command-state writer defect: ${JSON.stringify(outcome)} is not an outcome a row can be recorded with (ROW_OUTCOMES)`);+ if (outcome === 'drifted' ? !DRIFT_BEFORE.includes(patch.before) : patch.before !== undefined) {+ throw new TypeError(`command-state writer defect: ${JSON.stringify(outcome)} recorded with before ${JSON.stringify(patch.before)}`);+ }+ if (facts !== undefined && !(Array.isArray(facts) && factsShow(outcome, patch.before, facts))) {+ throw new TypeError(`command-state writer defect: ${JSON.stringify(outcome)}${patch.before ? ` after ${JSON.stringify(patch.before)}` : ''} is not what the row's facts show`);+ }+ return patch;+}++/**+ * The rows of one build invocation: each declared row's public result and its facts, kept across the build's own retries so a later attempt+ * says what an earlier one did. The publication observer, which lives for the invocation, owns one; a run without an observer (a dry run,+ * a direct caller) makes its own.+ */+function createCommandStateRowStore() {+ return { attempt: 0, rows: new Map() };+}++function fail(code, message, detail) {+ return new CommandStateError(code, `${message} — ${REMEDY[code] || 'see the message above'}`, detail);+}++/**+ * The build halt for a command-state refusal or unknown outcome: never retried automatically (lib/retry-policy.js RETRY.NEVER), with its code+ * and the CommandStateError as its cause. Any other error is returned as it is.+ */+function commandStateHalt(error, phase) {+ if (!(error instanceof CommandStateError)) return error;+ const { BuildHalt } = require('./entity-provision.js');+ const { RETRY } = require('./retry-policy.js');+ const halt = new BuildHalt(`${error.code}: ${error.message}`, { phase, code: error.code, recoverable: false, retry: RETRY.NEVER, cause: error });+ if (error.approvalDisplay) withApprovalDisplay(halt, error.approvalDisplay);+ return halt;+}++/**+ * The exact --authorize tokens an approval halt asks for, kept OFF the error's message: a halt's message reaches the generic build journal+ * (build-log.jsonl, build-status.json), where an exact approval token or row digest must not be stored. They ride on the error as a+ * non-enumerable `approvalDisplay` (so no serialization carries them either), which build-model-app.js prints to the maker with the halt, on+ * the console only; a direct caller reads it there. A dry run prints the same tokens.+ */+function withApprovalDisplay(error, text) {+ try {+ Object.defineProperty(error, 'approvalDisplay', { value: text, enumerable: false, configurable: true, writable: true });+ } catch { /* a frozen error keeps its message; a dry run still prints every token */ }+ return error;+}++/**+ * The offline check of the spec's commandStates (lib/command-state-contract.js validateCommandStates), as the build halt the engine throws+ * before it does anything else, or null when the declaration is absent, empty or valid. The engine runs it itself because a direct caller+ * (or the CLI with a structural profile, where these findings are only warnings) never passed through the App Spec validator: a supplied+ * value that is not valid (null, an object, an entry with a commands[] field or app scope) is refused, never treated as absent. Any+ * malformed entry makes it command-state-spec-invalid; app scope alone is command-state-app-scope-unverified.+ */+function commandStateSpecHalt(spec) {+ const { findings, errors } = validateCommandStates(spec);+ if (!findings.length) return null;+ const code = findings.some((f) => f.code === 'command-state-spec-invalid') ? 'command-state-spec-invalid' : 'command-state-app-scope-unverified';+ return commandStateHalt(fail(code, `the App Spec's commandStates is not valid: ${errors.join('; ')}`), 'preflight');+}++/**+ * Records, for each declared table, whether the build's existing table publication was seen to cover its latest command-row write. Every+ * callback is read-only and never throws: an observation it cannot make leaves the table unconfirmed, which only assertComplete acts on.+ */+function createCommandStatePublicationObserver() {+ const tables = new Map();+ const lc = (name) => String(name).toLowerCase();+ // The first publication seen since the table's latest row write is the one recorded: a later one of the same generation (the publish+ // phase's, after the envelope before the app) adds nothing, and keeps the path that a result already reported.+ const confirm = (entry, path) => {+ if (entry.outcome === 'confirmed' && entry.confirmation && entry.confirmation.generation === entry.generation) return;+ entry.outcome = 'confirmed';+ entry.confirmation = { generation: entry.generation, path };+ delete entry.reason;+ };+ const unconfirmedEntries = () => [...tables.values()].filter((t) => t.outcome !== 'confirmed');+ let rowsOf = () => [];+ const rowStore = createCommandStateRowStore();+ // What each unconfirmed table's rows are known to hold, worded from their facts by the one mapping (ROW_MESSAGES.publicationTable).+ const describeTable = (entry) => {+ let rows = [];+ try { rows = (rowsOf() || []).filter((r) => r && lc(r.entity) === entry.entity); } catch { rows = []; }+ return ROW_MESSAGES.publicationTable(entry.entity, rows);+ };+ const describeUnconfirmed = () => unconfirmedEntries().sort((a, b) => (a.entity < b.entity ? -1 : a.entity > b.entity ? 1 : 0)).map(describeTable).join('; ');+ const snapshot = () => [...tables.values()].sort((a, b) => (a.entity < b.entity ? -1 : a.entity > b.entity ? 1 : 0)).map((t) => ({+ entity: t.entity,+ outcome: t.outcome,+ basis: 'existing-before-app-table-envelope',+ ...(t.confirmation ? { path: t.confirmation.path } : {}),+ ...(t.outcome !== 'confirmed' ? { reason: t.reason, code: CODES.publishUnconfirmed } : {}),+ }));+ return {+ /** The row results of the attempt now running (createCommandStateRun), for a halt to carry. */+ trackRows(fn) { if (typeof fn === 'function') rowsOf = fn; },+ /** The invocation's rows and their facts (createCommandStateRowStore), which every attempt of the build adds to. */+ rowStore,+ /** A table every apply must see published, even when its rows already hold the declared flags (a save that was never published). */+ register(entity, rowIds = []) {+ const name = lc(entity);+ if (!tables.has(name)) tables.set(name, { entity: name, rowIds: new Set(), generation: 0, outcome: 'unconfirmed', reason: 'not-observed' });+ for (const id of rowIds) tables.get(name).rowIds.add(id);+ },+ declaredTables: () => [...tables.keys()].sort(),+ /** Before a row write is sent: a publication seen before it cannot have published it. */+ noteRowWrite(entity) {+ const entry = tables.get(lc(entity));+ if (!entry) return;+ entry.generation += 1;+ entry.outcome = 'unconfirmed';+ entry.reason = 'not-observed';+ delete entry.confirmation;+ },+ // Each observe* method takes the `path` that names the build's call site (sdk-build.js createTablePublication, which is the only+ // caller): the defaults are the paths before the app, the others are the publish phase's, the views phase's, a reconcile's, the app+ // publication's table scope and the end of the build's (e.g. `sdk-publish-phase`, `managed-publish-phase`).+ /** A plain PublishXml that names tables (the envelope before the app): only a non-empty list answered ok confirms, and only the names it carried. */+ observePlain(names, outcome, path = 'plain-before-app') {+ try {+ if (!Array.isArray(names) || !names.length) return;+ const ok = !!outcome && outcome.ok === true;+ for (const name of names) {+ const entry = tables.get(lc(name));+ if (!entry) continue;+ if (ok) confirm(entry, path);+ else if (entry.outcome !== 'confirmed') entry.reason = 'failed';+ }+ } catch { /* an observation that cannot be made confirms nothing */ }+ },+ /**+ * The SDK's publication of a table's artifact: the reconciled tables before the app (sdk-build.js publishReconciledTables), which follows+ * a refused or absent plain envelope, and the publish phase's. Only the names the caller proved published confirm: an answer of kind+ * submitted, verified or unverifiable whose publishScope is that table's entity envelope. A table it refused, or answered with no+ * request made, is not named, so it keeps the reason it had.+ */+ observeSdk(names, path = 'sdk-before-app') {+ try {+ if (!Array.isArray(names)) return;+ for (const name of names) { const entry = tables.get(lc(name)); if (entry) confirm(entry, path); }+ } catch { /* as above */ }+ },+ /**+ * The managed publisher's flush: only the names in `published` confirm; `withheld` says why a table did not, and `failed` names the table+ * whose publish was handed to the transport and halted (managed-scope-publisher.js flush `onHalt`), so it is never called unsent.+ */+ observeManaged(flushed, path = 'managed-before-app') {+ try {+ const published = flushed && Array.isArray(flushed.published) ? flushed.published : [];+ const withheld = flushed && Array.isArray(flushed.withheld) ? flushed.withheld : [];+ const failed = flushed && Array.isArray(flushed.failed) ? flushed.failed : [];+ for (const name of published) { const entry = tables.get(lc(name)); if (entry) confirm(entry, path); }+ for (const name of withheld) { const entry = tables.get(lc(name)); if (entry && entry.outcome !== 'confirmed') entry.reason = 'withheld'; }+ for (const name of failed) { const entry = tables.get(lc(name)); if (entry && entry.outcome !== 'confirmed') entry.reason = 'failed'; }+ } catch { /* as above */ }+ },+ unconfirmed: () => unconfirmedEntries().map((t) => t.entity).sort(),+ /** Each unconfirmed table with what its rows are known to hold, e.g. `new_ticket: saved, not published`. */+ describeUnconfirmed,+ /**+ * What a halt carries for this feature (not enumerable: it never reaches a serialized error, the journal or a retry's reading of the+ * error): `commandStates`, the rows and tables as they stand, and — while a declared table's publication is unconfirmed —+ * `commandStatePublicationError`. The halt's own code, cause and retry policy are left as they are.+ */+ attachFailure(error) {+ try {+ if (!error || typeof error !== 'object') return;+ const open = unconfirmedEntries();+ for (const entry of open) if (entry.reason === 'not-observed') entry.reason = 'halted-before-send';+ Object.defineProperty(error, 'commandStates', { value: { rows: rowsOf(), publication: snapshot() }, enumerable: false, configurable: true, writable: true });+ if (!open.length) return;+ const names = open.map((t) => t.entity).sort();+ Object.defineProperty(error, 'commandStatePublicationError', {+ value: { code: CODES.publishUnconfirmed, tables: names, message: `${describeUnconfirmed()} — required table publication was not confirmed; ${REMEDY[CODES.publishUnconfirmed]}.` },+ enumerable: false, configurable: true, writable: true,+ });+ } catch { /* a frozen error carries nothing */ }+ },+ snapshot,+ };+}++/**+ * One build attempt's command-state work.+ * @param {object} options+ * @param {object} options.spec - a validated App Spec with a non-empty commandStates+ * @param {object} options.transport - lib/command-state-transport.js, with `patchRow`+ * @param {string} options.origin - the environment, e.g. https://contoso.crm.dynamics.com+ * @param {{ rows?: Set<string>, tables?: Set<string> }} [options.approvals] - the exact --authorize tokens of this feature+ * @param {boolean} [options.publish] - the run publishes (an apply always does: commandStateMode)+ * @param {object|null} [options.observer] - createCommandStatePublicationObserver, or null (a dry run)+ */+function createCommandStateRun({ spec, transport, origin, approvals = {}, publish = true, observer = null } = {}) {+ const states = normalizeCommandStates(spec);+ const rowApprovals = approvals.rows instanceof Set ? approvals.rows : new Set();+ const tableApprovals = approvals.tables instanceof Set ? approvals.tables : new Set();+ const env = canonicalOrigin(origin);+ // The public result of each row, in the spec's order, with its facts: the invocation's own (the observer's store), so a retry of the build+ // keeps what an earlier attempt read and sent instead of starting each row again from `planned`.+ const store = observer && observer.rowStore ? observer.rowStore : createCommandStateRowStore();+ store.attempt += 1;+ const attempt = store.attempt;+ for (const s of states) {+ if (!store.rows.has(s.rowId)) store.rows.set(s.rowId, { entity: s.entity, location: s.bar, scope: s.scope, rowId: s.rowId, outcome: 'planned', changed: [], facts: [] });+ }+ const results = new Map(states.map((s) => [s.rowId, store.rows.get(s.rowId)]));+ let current = null;++ const label = (s) => `command state ${s.entity}/${s.bar}/${s.rowId}`;+ const record = (rowId, patch) => {+ const row = results.get(rowId);+ checkRowRecord(patch, row.facts);+ // A record replaces the row's whole step result: no `before` or `code` of an earlier record (an earlier attempt's) is carried into it.+ delete row.before;+ delete row.code;+ return Object.assign(row, patch);+ };+ const note = (rowId, fact) => { results.get(rowId).facts.push(Object.freeze({ attempt, ...fact })); };+ const history = (rowId) => renderRowHistory(results.get(rowId).facts);+ // An earlier attempt of this build sent a write to the row (one that may have landed): later messages must not say nothing was written.+ const sentBefore = (rowId) => results.get(rowId).facts.some((e) => counts(e) && e.attempt < attempt);++ function requireTransport({ write }) {+ const needs = ['get', 'getAbsolute', 'apiUrl', ...(write ? ['patchRow'] : [])];+ if (!transport || needs.some((name) => typeof transport[name] !== 'function')) {+ throw fail(CODES.transport, `commandStates: no ${write ? 'row reader and writer' : 'row reader'} was given to this build`);+ }+ if (!env) throw fail(CODES.transport, 'commandStates: the environment\'s https origin is not known');+ }++ // A row as the plan needs it, judged against the context: refused unless it is a candidate with a usable version. Every read is noted in the+ // row's facts (`phase`, READ_PHASES), whatever it found, before this returns or throws.+ async function readJudged(context, s, phase) {+ const table = context.tables.get(s.entity);+ const unreadable = (code) => note(s.rowId, { kind: 'read', phase, result: 'unreadable', code });+ let read;+ try {+ read = await readCommandStateRow(transport, s.rowId);+ } catch (error) {+ unreadable(error instanceof CommandStateError ? error.code : CODES.rowUnreadable);+ throw error;+ }+ if (!read.found) {+ unreadable(CODES.rowNotFound);+ throw fail(CODES.rowNotFound, `${label(s)}: the platform says the row does not exist`);+ }+ const decoded = decodeCommandStateRow(read.body, {+ rowId: s.rowId, entity: s.entity, metadataId: table.metadataId, appId: context.appId, inApp: table.inApp, location: s.location,+ optimisticConcurrency: context.optimisticConcurrency, requireVersion: true,+ });+ if (!decoded.eligible) {+ const code = codeForReasons(decoded.reasons) || CODES.rowUnreadable;+ unreadable(code);+ throw fail(code, `${label(s)}: ${decoded.reasons.join(', ')}${decoded.details.length ? ` (${decoded.details.join('; ')})` : ''}`);+ }+ note(s.rowId, { kind: 'read', phase, result: matches(s, decoded.row) ? 'matched' : 'differed', hidden: decoded.row.hidden, disabled: decoded.row.disabled });+ return { table, row: decoded.row };+ }++ function planItem(context, s, table, row) {+ const before = { hidden: row.hidden, isdisabled: row.disabled };+ const delta = diffCommandFlags(s.desired, before);+ const ids = { origin: env, appId: context.appId, tableId: table.metadataId, entity: s.entity, location: s.location, rowId: s.rowId };+ return {+ ...s, tableId: table.metadataId, appId: context.appId, caption: row.caption, before, etag: row.version, delta,+ approvalKey: Object.keys(delta).length ? commandStateApprovalKey({ ...ids, ifMatch: row.version, desired: s.desired }) : null,+ };+ }++ async function readPlan(phase) {+ const context = await resolveCommandStateContext(transport, { appUniqueName: spec.app.uniqueName, entities: [...new Set(states.map((s) => s.entity))] });+ if (!context.optimisticConcurrency) throw fail(CODES.versionUnavailable, 'commandStates: the table of commands does not keep row versions (optimistic concurrency is off)');+ const items = [];+ for (const s of states) {+ const { table, row } = await readJudged(context, s, phase);+ items.push(planItem(context, s, table, row));+ }+ const tables = [...new Set(items.map((i) => i.entity))].sort().map((entity) => {+ const first = items.find((i) => i.entity === entity);+ return { entity, token: commandTablePublishApprovalKey({ origin: env, appId: context.appId, tableId: first.tableId, entity }) };+ });+ return { context, items, tables };+ }++ // What one change is, for a maker deciding whether to approve it. The caption is the service's text (the row's `buttonlabeltext`), so it is+ // said only where the design shows labels — the approval display (console only) and a dry run's plan — and never in a halt's message,+ // which the build journal stores: there the row id names the button.+ function describe(item, { caption: withCaption = true } = {}) {+ const caption = !withCaption ? '' : item.caption === null ? ' (unlabelled)' : ` ${JSON.stringify(item.caption)}`;+ const changes = Object.keys(item.desired).map((key) => `${SPEC_FLAG[key]} ${item.before[key]} -> ${item.desired[key]}${item.before[key] === item.desired[key] ? ' (already)' : ''}`).join(', ');+ const disabledNote = Object.prototype.hasOwnProperty.call(item.delta, 'isdisabled') && item.delta.isdisabled+ ? '; disabled turns the modern command off for users (a ribbon equivalent can show instead) — it is not a security setting' : '';+ return `${item.entity} ${item.bar} button${caption} (row ${item.rowId}, table scope: every app that shows this table; stored hidden ${item.before.hidden}, disabled ${item.before.isdisabled}): ${changes}${disabledNote}`;+ }++ // Every approval the plan needs and does not have, in one stop.+ function checkApprovals(p) {+ const lines = [];+ const codes = new Set();+ for (const item of p.items) {+ if (!item.approvalKey || rowApprovals.has(item.approvalKey)) continue;+ const prefix = item.approvalKey.slice(0, item.approvalKey.lastIndexOf('/') + 1);+ const stale = [...rowApprovals].some((token) => token.startsWith(prefix));+ codes.add(stale ? CODES.approvalStale : CODES.approvalRequired);+ const why = stale ? ' — the approval given was for another version of this row or another intent' : '';+ lines.push([`${describe(item, { caption: false })}${why}`, item.approvalKey, `${describe(item)}${why}`]);+ }+ if (publish) {+ for (const table of p.tables) {+ if (tableApprovals.has(table.token)) continue;+ codes.add(CODES.publicationApprovalRequired);+ lines.push([`publish table ${table.entity}: publishes ALL saved customizations on it (anyone's), not only these buttons`, table.token]);+ }+ }+ if (!lines.length) return;+ const code = [CODES.approvalStale, CODES.approvalRequired, CODES.publicationApprovalRequired].find((c) => codes.has(c));+ // A retry of the build after an earlier attempt sent a row write cannot say "before this build writes anything": it says which rows.+ const earlier = states.filter((s) => sentBefore(s.rowId));+ const when = earlier.length+ ? `before this attempt writes anything (an earlier attempt of this build already sent a write: ${earlier.map((s) => `${label(s)}: ${history(s.rowId)}`).join('; ')})`+ : 'before this build writes anything';+ // The message names what needs approval; the tokens themselves, and the buttons' captions, go only to the approval display (withApprovalDisplay).+ throw withApprovalDisplay(+ fail(code, `commandStates: ${lines.length} approval${lines.length === 1 ? '' : 's'} needed ${when} (the exact --authorize tokens are printed with this halt, and by a dry run):\n ${lines.map(([what]) => what).join('\n ')}\n`),+ approvalDisplayOf(lines.map(([what, token, shown]) => [shown || what, token])),+ );+ }++ // Each declared flag, read back: identity and every flag the entry sets.+ const matches = (item, row) => Object.keys(item.desired).every((key) => (key === 'hidden' ? row.hidden : row.disabled) === item.desired[key]);++ async function readBack(item, phase) {+ try {+ const { row } = await readJudged(current.context, item, phase);+ return { ok: matches(item, row), row };+ } catch (error) {+ return { ok: false, error };+ }+ }++ // What the facts say a row's step ended as when this attempt had nothing to send: a row an earlier attempt wrote keeps that write's+ // outcome while every read since it has found the flags.+ function outcomeWithoutSend(facts) {+ const { send, reads } = sinceLastSend(facts);+ if (!send) return 'unchanged';+ if (reads.length && reads.every(matched)) return send.answer === ACKNOWLEDGED ? ACKNOWLEDGED : 'observed-matching-after-unknown-send';+ return 'unknown';+ }++ async function sendOne(item) {+ const { table, row } = await readJudged(current.context, item, 'own-step');+ const fresh = planItem(current.context, item, table, row);+ if (!fresh.approvalKey) {+ const outcome = outcomeWithoutSend(results.get(item.rowId).facts);+ if (outcome === 'unchanged') { record(item.rowId, { outcome, changed: [] }); return; }+ record(item.rowId, { outcome, changed: results.get(item.rowId).changed, ...(outcome === 'unknown' ? { code: CODES.notConfirmed } : {}) });+ if (outcome === 'unknown') throw fail(CODES.notConfirmed, `${label(item)}: ${history(item.rowId)}`);+ return;+ }+ if (!rowApprovals.has(fresh.approvalKey)) {+ const again = sentBefore(item.rowId) ? ` again (${history(item.rowId)})` : '';+ throw withApprovalDisplay(+ fail(CODES.approvalStale, `${label(item)}: the row changed since it was approved; it was not written${again} (its new --authorize token is printed with this halt, and by a dry run):\n ${describe(fresh, { caption: false })}\n`),+ approvalDisplayOf([[describe(fresh), fresh.approvalKey]]),+ );+ }+ const changed = Object.keys(fresh.delta).map((key) => SPEC_FLAG[key]);+ const flags = { ...fresh.delta };+ if (observer) observer.noteRowWrite(item.entity);+ let answer;+ let thrown;+ try {+ answer = await transport.patchRow(item.rowId, fresh.etag, fresh.delta);+ } catch (error) {+ if (error instanceof CommandStateError) throw error;+ thrown = error;+ }+ const status = answer && answer.status;+ const what = `${label(item)} (the write of ${flagWords(fresh.delta)})`;+ if (!thrown && (status === 200 || status === 204)) {+ note(item.rowId, { kind: 'send', answer: ACKNOWLEDGED, status, flags });+ const back = await readBack(fresh, 'readback');+ if (!back.ok) {+ record(item.rowId, { outcome: 'unknown', changed, code: CODES.notConfirmed });+ throw fail(CODES.notConfirmed, `${what}: ${history(item.rowId)}`);+ }+ record(item.rowId, { outcome: ACKNOWLEDGED, changed });+ return;+ }+ const refused = (code) => {+ note(item.rowId, { kind: 'send', answer: 'refused', status, flags });+ record(item.rowId, { outcome: 'refused', code });+ };+ if (!thrown && status === 404 && errorCode(answer.body) === NOT_FOUND) {+ refused(CODES.rowNotFound);+ throw fail(CODES.rowNotFound, `${label(item)}: the row no longer exists; it was not written (and is never created)`);+ }+ if (!thrown && status === 412) {+ refused(CODES.versionConflict);+ throw fail(CODES.versionConflict, `${label(item)}: the platform refused the write (HTTP 412): the row changed after it was read`);+ }+ // A definitive refusal: the request was authenticated and refused, so it changed nothing. 408 (timed out) and 429 (a limit) do not say+ // the write never started, so they are read like an unknown outcome below.+ if (!thrown && Number.isInteger(status) && status >= 400 && status < 500 && status !== 408 && status !== 429) {+ refused(CODES.updateRejected);+ throw fail(CODES.updateRejected, `${label(item)}: ${serviceAnswerText({ problem: 'write-refused', status, dataverseCode: errorCode(answer.body) })}`);+ }+ // No answer, a 5xx, 408, 429 or any status this does not expect (201, 202, 3xx): the write may have committed. It is never sent again; the+ // row is read once more and the outcome said as it is found.+ note(item.rowId, { kind: 'send', answer: 'lost', ...(thrown ? {} : { status }), flags });+ const back = await readBack(fresh, 'readback');+ if (back.ok) {+ record(item.rowId, { outcome: 'observed-matching-after-unknown-send', changed });+ return;+ }+ record(item.rowId, { outcome: 'unknown', changed, code: CODES.writeUnknown });+ // Why there was no answer, as readFailureText says it: the status and the system code (ECONNRESET), never the error's own text, which a+ // transport may fill with what the service said.+ const cause = thrown ? ` [${readFailureText(thrown)}]` : '';+ const mayLand = back.row && back.row.version === fresh.etag ? '; the row is still at the version the write was made against, so the write may still land' : '';+ throw fail(CODES.writeUnknown, `${what}: ${history(item.rowId)}${cause}${mayLand}`);+ }++ // The final proof (assertComplete): a fresh app context, then every declared row read and judged against it and its flags compared. Each+ // read is noted in the row's facts, so the preface (said after the reads) and a drifted row's message say what the reads found.+ // EVERY row is read, even after one has failed: a row read after the first failure would otherwise keep only its commands-phase facts, and+ // the halt and the result would say nothing of what it holds at the end. The halt is the first failure's — its code, its detail, its+ // wording — with the later failures' own messages after it; the code decides the retry policy and the exit, so those stay as they were.+ // Nothing is written here. An error that is not this feature's (a defect, a transport that broke its contract) still ends the proof at once.+ async function recheckAtCompletion() {+ try {+ requireTransport({ write: false });+ const context = await resolveCommandStateContext(transport, { appUniqueName: spec.app.uniqueName, entities: [...new Set(states.map((s) => s.entity))] });+ const failures = [];+ for (const s of states) {+ let row;+ try {+ ({ row } = await readJudged(context, s, 'final'));+ } catch (error) {+ if (!(error instanceof CommandStateError)) throw error;+ failures.push(error);+ continue;+ }+ if (!matches(s, row)) {+ // Its own remedy, not command-state-not-confirmed's: the commands phase read every row it wrote back holding the flags, so this+ // is a change made during the build, after that read. The row's recorded outcome stays what its step was.+ failures.push(new CommandStateError(CODES.notConfirmed, ROW_MESSAGES.finalDrift(rowResultOf(s.rowId))));+ }+ }+ if (failures.length) {+ const [first, ...later] = failures;+ throw new CommandStateError(first.code, [first.message, ...later.map((e) => e.message)].join('; '), first.detail);+ }+ } catch (error) {+ if (!(error instanceof CommandStateError)) throw error;+ throw new CommandStateError(error.code, `${ROW_MESSAGES.lateNote(rowResults())}: ${error.message}`, error.detail);+ }+ }+ // A step's refusal, as the build halt it ends the build with.+ async function step(phase, run) {+ try {+ return await run();+ } catch (error) {+ throw commandStateHalt(error, phase);+ }+ }++ const rowResultOf = (rowId) => { const r = results.get(rowId); return { ...r, changed: [...r.changed], facts: [...r.facts] }; };+ const rowResults = () => states.map((s) => rowResultOf(s.rowId));+ function result() {+ return { rows: rowResults(), publication: observer ? observer.snapshot() : [] };+ }+ // The observer outlives this attempt: it reports the invocation's rows (this attempt's declared rows, with every attempt's facts).+ if (observer && typeof observer.trackRows === 'function') observer.trackRows(rowResults);++ return {+ /** Read-only planning for a dry run: what each row holds, what would change, and the exact approvals the apply would need. */+ plan: () => step('plan', async () => {+ requireTransport({ write: false });+ const p = await readPlan('plan');+ return {+ rows: p.items.map((item) => ({+ entity: item.entity, location: item.bar, scope: item.scope, rowId: item.rowId, caption: item.caption, before: { ...item.before },+ desired: { ...item.desired }, change: { ...item.delta }, description: describe(item),+ ...(item.approvalKey ? { approval: item.approvalKey, approved: rowApprovals.has(item.approvalKey) } : {}),+ })),+ tables: p.tables.map((t) => ({ ...t, approved: tableApprovals.has(t.token) })),+ };+ }),+ /** Before the build's first write: every row, every approval; then the observer learns which tables must be published. */+ preflight: () => step('preflight', async () => {+ requireTransport({ write: true });+ current = await readPlan('preflight');+ checkApprovals(current);+ if (observer) for (const t of current.tables) observer.register(t.entity, current.items.filter((i) => i.entity === t.entity).map((i) => i.rowId));+ }),+ /** In the commands phase, before any row write: everything read again, and every remaining change still approved. */+ recheckAll: () => step('commands', async () => {+ requireTransport({ write: true });+ current = await readPlan('recheck');+ checkApprovals(current);+ }),+ /** One row at a time, then every row read once more before the build publishes. */+ applyRows: () => step('commands', async () => {+ if (!current) throw fail(CODES.transport, 'commandStates: rows applied before they were planned');+ for (const item of current.items) {+ try {+ await sendOne(item);+ } catch (error) {+ // A refusal before the send (the fresh read) leaves this row planned in the results: say it was refused, and why. Only when its facts+ // show no write that may have landed: anything else is a defect of this module, which must surface as itself, not as a second one.+ const row = results.get(item.rowId);+ if (row.outcome === 'planned' && factsShow('refused', undefined, row.facts)) record(item.rowId, { outcome: 'refused', code: error && error.code });+ throw error;+ }+ }+ for (const item of current.items) {+ const back = await readBack(item, 'after-every-row');+ if (!back.ok) {+ // The row matched after its own step (unchanged, acknowledged or observed-matching) and has lost the match since: its own outcome,+ // which keeps that history; the halt, the result line and the publication all word the row from its facts, which end with this read.+ record(item.rowId, { outcome: 'drifted', before: results.get(item.rowId).outcome, code: CODES.notConfirmed });+ throw fail(CODES.notConfirmed, ROW_MESSAGES.postWriteMismatch(rowResultOf(item.rowId)));+ }+ }+ }),+ /** The tables this attempt's rows are on. */+ requiredTables: () => [...new Set(states.map((s) => s.entity))].sort(),+ /**+ * After the build's shared work: every declared row judged again against the app and its tables as they are NOW, and every declared+ * table's publication confirmed, or exit 1. The context the commands phase resolved is not proof here: the build's own app work runs+ * after it and can take a table out of the app, so membership is resolved afresh. A refusal this late does not undo anything: the rows+ * already written stay written and a publication already sent stands, and each row's outcome stays what was observed.+ */+ assertComplete: () => step('publish', async () => {+ if (!observer) return;+ await recheckAtCompletion();+ const open = observer.unconfirmed();+ if (open.length) throw fail(CODES.publishUnconfirmed, `${observer.describeUnconfirmed()} — required table publication was not confirmed`);+ }),+ result,+ };+}++module.exports = {+ CODES, REMEDY, ROW_OUTCOMES, DRIFT_BEFORE, ROW_PHRASES, READ_PHASES, KIND_WHOLE, ROW_MESSAGES, renderRowHistory, rowKind, checkRowRecord, commandStateMode, commandStateHalt,+ commandStateSpecHalt, createCommandStateRun, createCommandStatePublicationObserver, createCommandStateRowStore,+};diff --git a/plugins/model-apps/scripts/lib/command-state-transport.js b/plugins/model-apps/scripts/lib/command-state-transport.jsnew file mode 100644index 000000000..d01a85b76--- /dev/null+++ b/plugins/model-apps/scripts/lib/command-state-transport.js@@ -0,0 +1,104 @@+'use strict';+// The one way the command-state feature talks to Dataverse: reads of the few resources it needs, by a path below the API root, and the one+// write it makes — a conditional PATCH of one command row's `hidden` / `isdisabled` (`patchRow`). It exposes no other write: no POST, no+// PublishXml, no DELETE, no `$batch`; publication stays on the build's own clients.+//+// It is built over the plugin's raw az-token client (`createAzHttpClient`, lib/sdk-http-client.js), which takes ABSOLUTE urls on the+// environment's origin and refuses any other, and over the SDK's own `dataverse.apiUrl(path)`, which says what the API root is — so the root+// is never guessed or pinned to a version here. The shared readers in lib/app-components.js call it the way they call the SDK's client:+// reader.get('/appmodules?$select=...') -> GET https://contoso.crm.dynamics.com/api/data/v9.0/appmodules?$select=...+// reader.getAbsolute('<the @odata.nextLink of a page>') -> the continuation, as the platform gave it+// reader.apiUrl('/appactions(...)') -> the absolute url, for a message+// Each answer is the raw client's `{ status, headers, body }`, the body parsed from JSON.+//+// Only the paths below are read, so a bug elsewhere cannot turn this into a general reader of the environment, and a continuation the platform+// gives must be under the same API root and name one of the same resources: a link anywhere else is refused before it is sent.++const { CommandStateError, ROW_VERSION, guidOf, serviceAnswerText } = require('./command-state-contract.js');++// The one write: PATCH <root>/appactions(<row id>), nothing after the parenthesis — no $select, no query.+const ROW_PATCH = /\/appactions\([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\)$/;++/**+ * The `sendOnce` of the raw client this feature writes with (createAzHttpClient's `deps.sendOnce`): the row PATCH is sent exactly once, whatever+ * answers it. A conditional PATCH answered 503 is otherwise sent again by the client (measured on the fake transport: two sends), and a second send+ * of a write that may have committed is refused 412 against the version the first one made, which reads exactly like another maker's edit.+ * Every read keeps the client's ordinary retries.+ */+function commandStateSendOnce(method, url) {+ return String(method).toUpperCase() === 'PATCH' && ROW_PATCH.test(String(url));+}++// The resources the feature reads, as the path below the API root starts.+const READ_PATHS = [+ /^\/appmodules\?/,+ /^\/appmodules\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublishedMultiple\(\)\?/,+ /^\/appmodulecomponents\?/,+ /^\/EntityDefinitions\(LogicalName='[a-z_][a-z0-9_]*'\)\?\$select=[A-Za-z,]+$/,+ /^\/EntityDefinitions\([0-9a-f-]{36}\)\?\$select=[A-Za-z,]+$/,+ /^\/appactions\?/,+ /^\/appactions\([0-9a-f-]{36}\)\?\$select=[a-z_,]+$/,+];++function unavailable(what) {+ return new CommandStateError('command-state-transport-unavailable', `command-state transport unavailable: ${what}`);+}++/**+ * @param {object} options+ * @param {{ get: Function, patch?: Function }} options.client - the raw client: absolute same-origin urls, `{ status, headers, body }` answers.+ * Without `patch` the transport has no `patchRow`, and a build that needs one refuses before it writes anything.+ * @param {(path: string) => string} options.apiUrl - the SDK's `dataverse.apiUrl`: a path below the API root -> its absolute url+ */+function createCommandStateTransport({ client, apiUrl } = {}) {+ if (!client || typeof client.get !== 'function') throw unavailable('no raw client to read with');+ if (typeof apiUrl !== 'function') throw unavailable('no API root to read under');+ // The API root, e.g. https://contoso.crm.dynamics.com/api/data/v9.0 — what every url this transport sends must start with.+ const root = String(apiUrl('/')).replace(/\/$/, '');+ let rootUrl;+ try {+ rootUrl = new URL(root);+ } catch {+ throw unavailable(`the API root '${root}' is not an absolute url`);+ }+ if (rootUrl.protocol !== 'https:') throw unavailable(`the API root '${root}' is not https`);++ const allowed = (path) => READ_PATHS.some((re) => re.test(path));+ // Neither refusal says the path or link it refused: a continuation is the service's text (a link can carry anything), and a path is+ // refused only when a defect built it, so naming it helps no maker. The words of a refused continuation are serviceAnswerText's.+ const refusePath = () => new CommandStateError('command-state-transport-unavailable', 'command-state transport: refused a read of a resource this feature does not read');+ const refuseLink = () => new CommandStateError('command-state-transport-unavailable', `command-state transport: ${serviceAnswerText({ problem: 'link-outside' })}`);++ const get = async (path) => {+ if (typeof path !== 'string' || !allowed(path)) throw refusePath();+ return client.get(`${root}${path}`);+ };+ // A continuation is absolute: it must be under the same root (same origin, same API version) and name an allowed resource.+ const getAbsolute = async (url) => {+ if (typeof url !== 'string' || !url.startsWith(`${root}/`) || !allowed(url.slice(root.length))) throw refuseLink();+ return client.get(url);+ };+ const surface = { get, getAbsolute, apiUrl: (path) => `${root}${path}` };+ if (typeof client.patch === 'function') {+ // PATCH /appactions(<rowId>) with If-Match: the exact observed version, and a body of only the flags that change, e.g.+ // If-Match: W/"4893215"+ // {"hidden":true}+ // No upsert: with If-Match the platform answers 412 rather than create a row+ // (https://learn.microsoft.com/power-apps/developer/data-platform/webapi/perform-conditional-operations-using-web-api).+ // No MSCRM.SolutionUniqueName header: this must never put a reused row into a solution.+ surface.patchRow = async (rowId, ifMatch, body) => {+ const id = guidOf(rowId);+ const keys = body && typeof body === 'object' && !Array.isArray(body) ? Object.keys(body) : [];+ // The values refused are not said: a row version is the service's tag, and the design keeps tags out of halts and journals.+ if (!id || id !== rowId) throw new CommandStateError('command-state-transport-unavailable', 'command-state transport: a row write names no row id');+ if (typeof ifMatch !== 'string' || !ROW_VERSION.test(ifMatch)) throw new CommandStateError('command-state-transport-unavailable', 'command-state transport: a row write carries no row version');+ if (!keys.length || keys.some((k) => (k !== 'hidden' && k !== 'isdisabled') || typeof body[k] !== 'boolean')) {+ throw new CommandStateError('command-state-transport-unavailable', 'command-state transport: a row write carries hidden and/or isdisabled, as true or false, and nothing else');+ }+ return client.patch(`${root}/appactions(${id})`, { ...body }, { headers: { 'If-Match': ifMatch } });+ };+ }+ return Object.freeze(surface);+}++module.exports = { createCommandStateTransport, commandStateSendOnce, READ_PATHS };diff --git a/plugins/model-apps/scripts/lib/configuration-artifacts.js b/plugins/model-apps/scripts/lib/configuration-artifacts.jsindex d2a648c04..66f31ab57 100644--- a/plugins/model-apps/scripts/lib/configuration-artifacts.js+++ b/plugins/model-apps/scripts/lib/configuration-artifacts.js@@ -2890,9 +2890,58 @@ async function locateExactly(ctx, port, kind, key) {const resolved = await port.resolve({ kind, key: portKeyOf(kind, key) });if (!resolved || resolved.state !== 'present' || typeof resolved.id !== 'string' || !resolved.id) throw identityStop('create-identity-unverified');await refuseLocalDraft(ctx.sdk, kind, resolved.id);- return { id: resolved.id, remote: await ctx.sdk.fetchArtifact(kind, resolved.id, { overwrite: true }), origin: 'resolved' };+ // A protected rule's conditions are paired at the ids its binding holds, as the build's plan pairs them (lib/configuration-protected.js+ // locateItem): a swap of two bound rows' criteria is an edit the build refuses (configuration-edit-unsupported), so verify must not+ // pass it. Content pairing alone would. Only a rule takes them: the other kinds are compared as before.+ const boundChildIds = kind === 'duplicateRule' && resolved.childIds && typeof resolved.childIds === 'object' ? resolved.childIds : undefined;+ return {+ id: resolved.id, remote: await ctx.sdk.fetchArtifact(kind, resolved.id, { overwrite: true }), origin: 'resolved',+ ...(boundChildIds ? { childIds: boundChildIds } : {}),+ ...(kind === 'duplicateRule' && resolved.buildRefusal ? { buildRefusal: resolved.buildRefusal } : {}),+ };}+// What a protected rule's definition check names, as the union of two judgments: the content comparison (`compared`, whose pointers+// keep the order the unprotected check reports them in) and the build's own (`found.buildRefusal`, from the port: it refuses every+// edit of a protected rule). Placement rules, so a consumer that reads the fields sees one stable shape:+// - the comparison's pointers stay where they are; a pointer only the build's judgment adds goes after them;+// - each `/conditions/<key>` follows `/conditions` at once, in declaration order: a declared condition the plan would create+// (a new or renamed key) or whose bound row no longer holds its criteria;+// - a removal (a bound row no longer declared, an extra row) names `/conditions` alone;+// - `/definition` only when the build refuses and nothing above says what: a state change the declaration does not name.+// A content refusal does not hide a build refusal: the build still refuses, so the check is DRIFT, naming the root pointer when+// the refusal is a root field (these refusals stop the comparison before it names anything).+const CONTENT_REFUSAL_POINTER = { DUPLICATE_RULE_TABLE_IMMUTABLE: '/matchingEntity', DUPLICATE_RULE_NAME_CONFLICT: '/entity', CONFIGURATION_CHILD_IDENTITY_AMBIGUOUS: '/conditions' };++function ruleDriftFields(entry, found, compared) {+ const refusal = found.buildRefusal;+ const out = compared.refusal+ ? (CONTENT_REFUSAL_POINTER[compared.refusal] ? [CONTENT_REFUSAL_POINTER[compared.refusal]] : [])+ : compared.changes.filter((c) => !c.binding).map((c) => c.pointer);+ if (refusal || out.includes('/conditions')) {+ const keyed = conditionDriftPointers(entry, found.remote, found.childIds, new Set(refusal ? refusal.created : []));+ if (!out.includes('/conditions') && (keyed.length || (refusal && refusal.removed))) out.push('/conditions');+ const at = out.indexOf('/conditions');+ if (at >= 0) out.splice(at + 1, 0, ...keyed.filter((pointer) => !out.includes(pointer)));+ }+ return refusal && !out.length ? ['/definition'] : out;+}++// The declared conditions of a protected rule that the build's plan would create (`created`, by key), or whose bound row no+// longer holds their criteria, as drift pointers (`/conditions/<key>`), in declaration order, so a failing check names them.+// `bound` is the binding's slot -> id (slot = condition key). A bound row that is gone never gets here: the port reads every+// bound row at its id (configuration-row-not-found).+function conditionDriftPointers(entry, remote, bound, created = new Set()) {+ const rows = Array.isArray(remote.conditions) ? remote.conditions : [];+ const out = [];+ for (const d of Array.isArray(entry.conditions) ? entry.conditions : []) {+ if (created.has(d.key)) { out.push(`/conditions/${d.key}`); continue; }+ const id = has(bound, d.key) ? bound[d.key] : null;+ const row = id ? rows.find((r) => ref(r.id) === ref(id)) : null;+ if (row && !describes(d, row)) out.push(`/conditions/${d.key}`);+ }+ return out;+}async function verifyKind(ctx, kindPlan, entries, checks, onFound) {for (const entry of entries) {const { kind } = kindPlan;@@ -2915,10 +2964,12 @@ async function verifyKind(ctx, kindPlan, entries, checks, onFound) {if (found.refusal) { checks.push({ kind, key, name: 'definition', ok: false, code: found.refusal }); continue; }if (onFound) onFound(entry, found);const compared = kindPlan.compare(entry, found.remote, ctx, found.childIds);- if (compared.refusal) { checks.push({ kind, key, name: 'definition', ok: false, code: compared.refusal }); continue; }- const drift = compared.changes.filter((c) => !c.binding).map((c) => c.pointer);- const bindingDrift = compared.changes.filter((c) => c.binding).map((c) => c.pointer);- checks.push(drift.length ? { kind, key, name: 'definition', ok: false, code: 'DRIFT', fields: drift } : { kind, key, name: 'definition', ok: true });+ // A protected rule the build refuses is DRIFT whatever the comparison said (ruleDriftFields); otherwise a refusal stands.+ const ruleRefused = kind === 'duplicateRule' && found.buildRefusal;+ if (compared.refusal && !ruleRefused) { checks.push({ kind, key, name: 'definition', ok: false, code: compared.refusal }); continue; }+ const fields = kind === 'duplicateRule' && found.childIds ? ruleDriftFields(entry, found, compared) : compared.changes.filter((c) => !c.binding).map((c) => c.pointer);+ const bindingDrift = (compared.changes || []).filter((c) => c.binding).map((c) => c.pointer);+ checks.push(fields.length ? { kind, key, name: 'definition', ok: false, code: 'DRIFT', fields } : { kind, key, name: 'definition', ok: true });const bindings = bindingsOf(ctx);const bound = kind === 'environmentVariable' ? bindings.environmentVariables.has(lower(key)): kind === 'connectionReference' ? bindings.connectionReferences.has(lower(key)) : false;diff --git a/plugins/model-apps/scripts/lib/configuration-protected.js b/plugins/model-apps/scripts/lib/configuration-protected.jsindex 6f23fd205..e079a11f3 100644--- a/plugins/model-apps/scripts/lib/configuration-protected.js+++ b/plugins/model-apps/scripts/lib/configuration-protected.js@@ -173,6 +173,19 @@ async function locateItem(env, kind, key) {return { state: 'bound', planned };}+/**+ * The read-only first step of the build's judgment of a bound item (the preflight, and verify for a rule): what its plan would+ * change (editShapeOf) as { shape }, or as { halt: { code, message, id? } } when nothing can be judged from it — a read that+ * did not complete (create-identity-unverified), or a bound row that is gone (configuration-row-not-found, never replaced by+ * a namesake). One function, so verify and the build cannot read the same state two ways. It sends nothing.+ */+async function judgeBoundShape(dataverse, kind, planned) {+ const shape = await B.editShapeOf(dataverse, planned);+ if (shape.state !== 'complete') return { halt: { code: UNVERIFIED_CODE, message: `the ${kind} "${planned.key}" could not be read completely` } };+ if (shape.missing.length) return { halt: { id: shape.missing[0].id, code: B.NOT_FOUND_CODE, message: `a bound row of ${kind} "${planned.key}" is gone; it is not replaced by a namesake` } };+ return { shape };+}+/*** The verdict on a bound item's edit (editShapeOf), or null when the protected path can make it:* a rule: any change at all is unsupported (created, published once, then only verified);@@ -522,9 +535,9 @@ async function preflightProtectedConfiguration({ spec, store, ctx, dataverse, so// removal the protected path does not make, authorized or not. A settings entry that leaves the value alone ("" or// none) or replaces it is not a clear; those keep the ordinary path and its authorization.const clears = kind === 'environmentVariable' && clearsValue(bindings, item.planned.key);- const shape = await B.editShapeOf(dataverse, item.planned);- if (shape.state !== 'complete') { halts.push({ kind, key: item.planned.key, code: UNVERIFIED_CODE, message: `the ${kind} "${item.planned.key}" could not be read completely` }); continue; }- if (shape.missing.length) { halts.push({ kind, key: item.planned.key, id: shape.missing[0].id, code: B.NOT_FOUND_CODE, message: `a bound row of ${kind} "${item.planned.key}" is gone; it is not replaced by a namesake` }); continue; }+ const judged = await judgeBoundShape(dataverse, kind, item.planned);+ if (judged.halt) { halts.push({ kind, key: item.planned.key, ...judged.halt }); continue; }+ const { shape } = judged;// A clear plans no value row, so a value row under the definition is the removal the clear would send.const verdict = clears ? (shape.removals.length ? { code: B.DELETE_CODE, message: VALUE_REMOVAL_MESSAGE } : null): kind === 'customApi' || kind === 'duplicateRule' ? editVerdict(kind, shape)@@ -805,7 +818,8 @@ function manifestStore(manifest) {/*** Verify's port for the protected kinds (verify-model-app.js, under the opt-in): the same exact location the build uses* (locateItem), over the workspace's binding store as verify reads it (`manifest`), and READ-ONLY — it never sends, settles- * or recovers anything. resolve({ kind, key }) answers { state: 'present', id } for a committed binding whose rows all+ * or recovers anything. resolve({ kind, key }) answers { state: 'present', id, childIds } (the bound child rows, slot -> id) for a+ * committed binding whose rows all* read present at their exact ids; anything else throws, typed, and verify reports that code for the item:* configuration-row-not-found a bound row is gone (a namesake elsewhere never stands in);* managed-settlement-pending an attempt is still pending: nothing is proved yet (verify-spec.js lists it unverified);@@ -820,7 +834,31 @@ function protectedVerifyPort({ spec, manifest, dataverse, solution, bindings })protects: (kind) => KINDS.has(kind),async resolve({ kind, key }) {const item = await locateItem(await env(), kind, key);- if (item.state === 'bound') return { state: 'present', id: item.planned.plan.rows[0].id };+ // The ids of the child rows the binding holds (slot -> id): verify pairs a rule's conditions at them, as the build's plan does+ // (configuration-artifacts.js locateExactly). A declared child the binding does not hold yet is planned as a create at+ // a derived id: that id is not bound to anything, so it is left out.+ // A bound rule is judged as the build's preflight judges it (judgeBoundShape + editVerdict over the same plan), read-only, so+ // verify refuses what a build would refuse: a condition the plan would create (a new or renamed key), a bound or extra row+ // the declaration does not name, a changed rule, an omitted `conditions` over bound ones. What the preflight cannot judge+ // (an incomplete read, a bound row gone) throws here with its own typed code. The refusal rides along as data: verify+ // still reports the content differences, and fails when either finds one.+ if (item.state === 'bound') {+ const childIds = Object.fromEntries(item.planned.rows.filter((r) => r.slot !== null && r.mode === 'update').map((r) => [r.slot, r.id]));+ const out = { state: 'present', id: item.planned.plan.rows[0].id, childIds };+ if (kind === 'duplicateRule') {+ const judged = await judgeBoundShape((await env()).dataverse, kind, item.planned);+ if (judged.halt) throw stop(judged.halt.code, judged.halt.message, { kind, key: item.planned.key, ...(judged.halt.id ? { id: judged.halt.id } : {}) });+ const verdict = editVerdict(kind, judged.shape);+ if (verdict) {+ out.buildRefusal = {+ code: verdict.code,+ created: item.planned.rows.filter((r) => r.kind === 'duplicateRuleCondition' && r.mode === 'create').map((r) => r.slot),+ removed: judged.shape.removals.length > 0,+ };+ }+ }+ return out;+ }if (item.state === 'pending') throw stop(PENDING_CODE, `the ${kind} "${item.planned.key}" has an attempt still pending; it is not verified until a build settles it`, { kind, key: item.planned.key });throw stop(UNVERIFIED_CODE, `the ${kind} "${item.planned.key}" has no committed binding in this workspace's binding store; it is never verified by name`, { kind, key: item.planned.key });},diff --git a/plugins/model-apps/scripts/lib/deployed-baseline.js b/plugins/model-apps/scripts/lib/deployed-baseline.jsindex 3db9196db..f2772b01b 100644--- a/plugins/model-apps/scripts/lib/deployed-baseline.js+++ b/plugins/model-apps/scripts/lib/deployed-baseline.js@@ -131,7 +131,11 @@ function writeBaseline(workspaceDir, spec, { appDir, environment, appUniqueName,// truncated file, which reads as no baseline — and without one the spec wins over every nav change made// in the designer. A failed write now leaves the previous snapshot of this app and environment, which is// still right about everything the latest apply did not change.- writeFileAtomic(baselinePath(workspaceDir), JSON.stringify(snapshot));+ // One rename, no retry through a Windows file lock ({ retryLock: false }): download-model-app.js writes this file+ // WITHOUT the app's build lease, so an older write that was refused and retried could land after a newer build's+ // write under the lease and put the older baseline back (the build would then overwrite the maker's designer edits).+ // A refused write keeps failing with its original error, which callers already treat as non-fatal.+ writeFileAtomic(baselinePath(workspaceDir), JSON.stringify(snapshot), { retryLock: false });}/**diff --git a/plugins/model-apps/scripts/lib/entity-provision.js b/plugins/model-apps/scripts/lib/entity-provision.jsindex 255a0cff9..61b16850c 100644--- a/plugins/model-apps/scripts/lib/entity-provision.js+++ b/plugins/model-apps/scripts/lib/entity-provision.js@@ -1800,8 +1800,11 @@ function makeRunner({ emit, total, throttle }) {emit(outcome({ phase, status: 'skip', label: `${label} (${typeof why === 'string' ? why : 'exists'})`, n: myN, total }));return undefined;}- emit(outcome({ phase, status: 'error', label, n: myN, total, detail: String((err && err.message) || err) }));- throw new BuildHalt(`${phase} failed: ${(err && err.message) || err}${operatorRemedy(err)}`, { phase, code: (err && err.code) || 'sdk-error', recoverable, cause: err, retry: retryPolicyFor(err) });+ // A build with commandStates marks an error thrown at a table publication with the checked words the halt says of it+ // (command-state-contract.js withCheckedDisplay); any other error, and every error without commandStates, is said by its own.+ const shown = require('./command-state-contract.js').checkedDisplay(err);+ emit(outcome({ phase, status: 'error', label, n: myN, total, detail: shown.text }));+ throw new BuildHalt(`${phase} failed: ${shown.text}${operatorRemedy(err)}`, { phase, code: shown.code, recoverable, cause: err, retry: retryPolicyFor(err) });}};const skip = (phase, label) => { emit({ phase, status: 'skip', label, n: (n += 1), total }); };diff --git a/plugins/model-apps/scripts/lib/managed-feature-contract.js b/plugins/model-apps/scripts/lib/managed-feature-contract.jsindex 030298f7a..bf1540dc9 100644--- a/plugins/model-apps/scripts/lib/managed-feature-contract.js+++ b/plugins/model-apps/scripts/lib/managed-feature-contract.js@@ -1050,6 +1050,10 @@ async function confirmUncertainPublication({ store, barrier, scope, client, read// success, as before. Returns the failure to raise, or null.const PUBLISH_ANSWERED = new Set(['submitted', 'verified', 'unverifiable']);const PUBLISH_NOT_REQUESTED = new Set(['none', 'notApplicable', 'notRequested']);+// Whether a publishArtifact answer is positive proof that its publish request was sent and answered success: only the kinds above that+// say so. A no-request kind (the real SDK answers `notApplicable` for an artifact it has nothing to publish for, sending nothing), a+// failure, an unknown kind and an answer with no kind prove nothing. `shipped` is not read: a `submitted` answer has `shipped: false`.+const publishAnswerProvesPublication = (answer) => !!(answer && answer.publish && typeof answer.publish === 'object' && PUBLISH_ANSWERED.has(answer.publish.kind));// How long publishManagedScope waits before each repeated read-back of a publish whose first read does not show it yet:// 45 s in all, as the live reads that first agreed came 42 s after the publish answered (see the read-back below).@@ -1395,6 +1399,7 @@ async function publishManagedScope({ store, barrier, scope, groups, client, read}module.exports = {PUBLICATION_UNVERIFIED,+ publishAnswerProvesPublication,PUBLICATION_UNCONFIRMED,PUBLICATION_REFUSED,LAYER_READER_MISSING,diff --git a/plugins/model-apps/scripts/lib/managed-scope-publisher.js b/plugins/model-apps/scripts/lib/managed-scope-publisher.jsindex 32afb848c..028d797b1 100644--- a/plugins/model-apps/scripts/lib/managed-scope-publisher.js+++ b/plugins/model-apps/scripts/lib/managed-scope-publisher.js@@ -83,14 +83,22 @@ function createManagedTablePublisher({ store, barrier, client, halt, settle } =* Publish `tables` (those of them that are routed) through the managed coverage protocol, one at a time and one* publish each. Answers { published: [table], withheld: [table] }; throws the halt for a refusal. Serialized: two* flushes never interleave, so a table is never published twice in parallel.+ * `onHalt(partial)`, optional: told, just before a table's halt is thrown, what this flush settled before it —+ * { published, withheld, failed } where `failed` names that table when its publish was handed to the transport (an+ * observer must not report it as never sent). It is only told: what it does or throws never changes the halt.+ * `sayRefusal(outcome)`, optional: words a refused or unanswered PublishXml (publishTablesXml's `{ ok: false, facts }`, asked for its+ * checked facts) for the error the halt carries, in place of its reason. A build with commandStates passes it (sdk-build.js+ * createTablePublication): a failure the client met before the request was dispatched is thrown as it is (publishManagedScope), so the+ * reason, which quotes the service's text, would reach the halt's finding. Without it the call and the error are the ones 2.23.0 made.*/- function flush(tables, { phase = 'publish', path = 'managed publication' } = {}) {+ function flush(tables, { phase = 'publish', path = 'managed publication', onHalt, sayRefusal } = {}) {const run = chain.then(async () => {const published = [];const withheld = [];for (const table of [...new Set((tables || []).map(lc))].filter(routed)) {const label = `the publish of table ${table}`;let out;+ let handed = false;try {out = await publishManagedScope({store, barrier, client, path, settle,@@ -101,12 +109,18 @@ function createManagedTablePublisher({ store, barrier, client, halt, settle } =// A refused PublishXml is RETURNED (the client answers { status }, publishTablesXml { ok: false }), so it is// thrown here: returning normally would let the read-back "confirm" a carried group live before the send.// Never `definiteNoStart`: an answer, or the lack of one, is not proof the publish never started.- const r = await publishTablesXml(client, [table]);- if (!r.ok) throw Object.assign(new Error(r.reason || `the publish of table ${table} was refused`), { code: 'publish-failed' });+ handed = true;+ const words = typeof sayRefusal === 'function';+ const r = words ? await publishTablesXml(client, [table], { facts: true }) : await publishTablesXml(client, [table]);+ if (!r.ok) throw Object.assign(new Error((words ? sayRefusal(r) : r.reason) || `the publish of table ${table} was refused`), { code: 'publish-failed' });},});} catch (err) {- throw halt(phase, label, (err && err.code) || 'managed-not-settled', { cause: err, findings: [{ key: table, code: (err && err.code) || 'managed-not-settled', message: String((err && err.message) || err) }] });+ const stop = halt(phase, label, (err && err.code) || 'managed-not-settled', { cause: err, findings: [{ key: table, code: (err && err.code) || 'managed-not-settled', message: String((err && err.message) || err) }] });+ if (typeof onHalt === 'function') {+ try { onHalt({ published: [...published], withheld: [...withheld], failed: handed ? [table] : [] }); } catch { /* told only */ }+ }+ throw stop;}if (out.withheld) withheld.push(table);else { published.push(table); barrier.routePaid(table); }diff --git a/plugins/model-apps/scripts/lib/phase-diff.js b/plugins/model-apps/scripts/lib/phase-diff.jsindex 9cbeb3d47..9f9076d38 100644--- a/plugins/model-apps/scripts/lib/phase-diff.js+++ b/plugins/model-apps/scripts/lib/phase-diff.js@@ -41,7 +41,9 @@ const PHASE_SLICES = {// so their edits force a full build and record debt rather than a silent skip.'business-rules': (s) => s.businessRules,'business-process-flows': (s) => s.businessProcessFlows,- commands: (s) => s.commands,+ // commandStates[] are applied in the commands phase. Only a spec that declares some compares them, ordered by row id (their order means+ // nothing): a spec without them diffs exactly as before. A change to them is a full build (classify-changes.js).+ commands: (s) => (hasCommandStates(s) ? { commands: s.commands, commandStates: commandStatesByRow(s.commandStates) } : s.commands),dashboards: (s) => s.dashboards,'app-shell': (s) => ({ app: s.app, appShell: s.appShell }),pages: (s) => s.pages,@@ -55,6 +57,14 @@ const PHASE_SLICES = {security: (s) => ({ personas: s.personas, roleGrants: s.roleGrants }),};+function hasCommandStates(s) {+ return !!s && Array.isArray(s.commandStates) && s.commandStates.length > 0;+}+function commandStatesByRow(states) {+ const key = (e) => String((e && e.rowId) || '').toLowerCase();+ return [...states].sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0));+}+// Deterministic, key-order-independent JSON so a reordered-but-equal slice compares equal. Arrays keep// their order (order is semantic for views/columns/sitemap); only object KEYS are sorted.function stableStringify(value) {diff --git a/plugins/model-apps/scripts/lib/rename-retry.js b/plugins/model-apps/scripts/lib/rename-retry.jsnew file mode 100644index 000000000..fa3ea2c94--- /dev/null+++ b/plugins/model-apps/scripts/lib/rename-retry.js@@ -0,0 +1,110 @@+'use strict';+// One rename that survives a brief Windows file lock.+//+// The plugin's state files (the managed binding store, the changed-only snapshot, its markers and the other+// records written temp-then-rename) become durable with `rename(temp, target)`. On Windows a rename fails+// with EPERM, EACCES or EBUSY while another process holds the source or the target open: antivirus or the+// search indexer scanning the file that was just written, a backup or sync client, a second build reading+// the store. The hold ends in milliseconds to seconds, and a build that gives up at the first refusal fails+// a whole run (`managed-binding-write-failed`, "the changed-only snapshot ... could not be invalidated") for+// a condition that was about to clear. libuv does not retry; graceful-fs retries renames on win32 for the+// same reason.+// https://learn.microsoft.com/en-us/windows/win32/fileio/obtaining-a-handle-to-a-file-or-directory (sharing modes)+// https://nodejs.org/api/errors.html#common-system-errors (EPERM, EACCES, EBUSY)+//+// The contract:+// * Windows only, and only for a refusal that is one of those three codes. Any other platform, and any other+// code (ENOENT, EXDEV, ENOSPC...), is exactly one attempt, as before.+// * The wait is bounded twice (see the two numbers below). A hold that outlasts the bound is a real lock, and+// the caller gets the ORIGINAL error from the LAST attempt, untouched (same code, syscall, path, message), so+// every caller's own message and exit code stay what they were.+// * A retry only ever repeats the same rename, so it stays atomic: a refused rename moved nothing.+// A caller must be able to say why repeating its rename is safe: its temp file is its own and unique to the+// attempt, and the target is a file the plugin owns, written under a lease or compare-and-set; see each call+// site. A path that an actor outside the plugin can replace while the wait goes on (a maker's file, a folder+// that is about to be deleted) must NOT use this: the wait would let a decision made before it go stale.++const RENAME_LOCK_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']);++// The wait is synchronous (Atomics.wait): nothing else in the process runs meanwhile, not the heartbeat of a+// teardown (a beat every 60 s; a teardown with no beat for 5 min is taken for dead), not an HTTP callback (the+// transport times out a read after 60 s and a write after 300 s). So the wait is capped twice:+// * RENAME_RETRY_BUDGET_MS, 5 s: the most one rename waits. A chosen bound, not a measured hold: long enough for a+// scanner or an indexer to let go of a file just written, short enough to stay well inside the limits above.+// * PROCESS_WAIT_TOTAL_MS, 30 s: the most this process waits out locks in all, across every rename. Once the+// time spent reaches it, every later refused rename is ONE attempt, exactly as it was before this module, so+// a lock that really is held cannot add up to minutes of blocking over many writes (a teardown that records+// several receipts, a build that writes a record per step). 30 s is half of the 60 s beat, a tenth of the+// 5 min staleness and well inside the transport's timeouts.+// No production path can raise either number; only a test can change them (setDefaultBudgetMs and+// setProcessWaitedMs, through tests/helpers/short-rename-wait.js, which restores them).+const RENAME_RETRY_BUDGET_MS = 5000;+const PROCESS_WAIT_TOTAL_MS = 30000;+const FIRST_PAUSE_MS = 25;+// Doubling from 25 ms would reach tens of seconds in a few steps; a cap keeps polling often enough to land+// soon after the hold ends.+const MAX_PAUSE_MS = 1000;++let defaultBudgetMs = RENAME_RETRY_BUDGET_MS;+// The time this process has spent waiting out locks (the pauses asked for), against PROCESS_WAIT_TOTAL_MS. A new+// process starts at zero.+let processWaitedMs = 0;++// Tests that make every rename fail for good on Windows use this to keep the wait to a moment. Returns the+// previous value so a test can restore it.+function setDefaultBudgetMs(ms) {+ const previous = defaultBudgetMs;+ defaultBudgetMs = ms;+ return previous;+}++// Sets (and returns the previous) time this process has already spent waiting: a test starts from 0 and puts the+// old value back, so no test leaves a spent budget to the next one.+function setProcessWaitedMs(ms) {+ const previous = processWaitedMs;+ processWaitedMs = ms;+ return previous;+}++function sleepSync(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++// A directory where the file is to go is refused for good, never for a moment: on Windows `rename(file, directory)`+// answers EPERM, and no scanner letting go changes that. Waiting for it (a receipt path that a folder holds,+// say) would only delay the same error. Any doubt (a stat that fails, an fs without `lstatSync`) is "not+// that case", so the lock is waited out.+function targetIsADirectory(fsImpl, from, to) {+ try {+ return fsImpl.lstatSync(to).isDirectory() && !fsImpl.lstatSync(from).isDirectory();+ } catch {+ return false;+ }+}++// `fsImpl` is the fs the caller already writes through (a test seam). `opts`: `budgetMs` (a lower wait for this+// call than the default), `pause(ms)` (how to wait), `platform` (default process.platform): the last two are+// seams for tests, never for callers.+function renameWithRetry(fsImpl, from, to, opts) {+ const o = opts || {};+ const budget = typeof o.budgetMs === 'number' ? Math.min(o.budgetMs, defaultBudgetMs) : defaultBudgetMs;+ const pause = o.pause || sleepSync;+ const platform = o.platform || process.platform;+ let waited = 0;+ let next = FIRST_PAUSE_MS;+ for (;;) {+ try {+ fsImpl.renameSync(from, to);+ return;+ } catch (err) {+ if (platform !== 'win32' || !err || !RENAME_LOCK_CODES.has(err.code) || waited >= budget || processWaitedMs >= PROCESS_WAIT_TOTAL_MS || targetIsADirectory(fsImpl, from, to)) throw err;+ const wait = Math.min(next, budget - waited, PROCESS_WAIT_TOTAL_MS - processWaitedMs);+ pause(wait);+ waited += wait;+ processWaitedMs += wait;+ next = Math.min(next * 2, MAX_PAUSE_MS);+ }+ }+}++module.exports = { renameWithRetry, setDefaultBudgetMs, setProcessWaitedMs, sleepSync, RENAME_LOCK_CODES, RENAME_RETRY_BUDGET_MS, PROCESS_WAIT_TOTAL_MS };diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.jsindex 355bcbb83..f3b307677 100644--- a/plugins/model-apps/scripts/lib/sdk-build.js+++ b/plugins/model-apps/scripts/lib/sdk-build.js@@ -175,6 +175,9 @@ const { isDeclaredView, declaredViewKey, planViewReconcile, applyViewReconcile }const { isDeclaredChart, declaredChartKey, planChartReconcile, applyChartReconcile } = require('./chart-reconcile.js');const { openManagedContext, isStoreEnvironment, attemptProvenUnsent, discoverManagedStore, ROW_FAMILIES } = require('./managed-bindings.js');const { isManagedEntity, planCommandReconcile, applyCommandReconcile } = require('./command-reconcile.js');+const { commandStateMode, commandStateSpecHalt, createCommandStateRun, createCommandStatePublicationObserver, CODES: COMMAND_STATE_CODES, REMEDY: COMMAND_STATE_REMEDY } = require('./command-state-run.js');+const { createCommandStateTransport } = require('./command-state-transport.js');+const { serviceAnswerText, withCheckedDisplay } = require('./command-state-contract.js');const { planQuickFind, applyQuickFind } = require('./quick-find.js');const { HTTP_SEND_HISTORY } = require('./sdk-http-client.js');// The configuration kinds (environment variables, connection references, Custom APIs, duplicate rules) and the solution's version:@@ -3233,15 +3236,26 @@ function partialEnrichment(error) {// in force once the app is published, and the publish phase is what does that. `failed`: `{ target, error }` for each// TABLE target whose last publish the SDK refused by value (`publish.kind === 'failed'`, after the retry below), so its// saved changes are not live. This function only reports one (a warning); publishReconciledTables, which must not let-// the app be published ahead of such a table, halts on it.-async function publishTargets(provision, runner, concurrency, entityTargets, appTarget, warn, { keepGoing = false } = {}) {+// the app be published ahead of such a table, halts on it. `publishedTargets`: each TABLE target (the same array) whose last+// publish answered with positive proof that it was sent and succeeded (`proves` below, after the retry) — what publishReconciledTables+// tells the commandStates observer was published; a caller that does not read it sees nothing new. `answers`: each target (the same+// array) -> the answer its last publish gave (the envelope's, or its retry's), which createTablePublication reads for the table the+// publish named (publishScope).+//+// `checked` is for a build with commandStates (createTablePublication passes it): every line it prints about a failed publish says only+// the checked facts of the answer (reportTablePush), never its text. Without it every line is the one 2.23.0 printed. `onProven(target,+// answer)`: told of each table target as soon as its answer proves its publication (createTablePublication's observer), so a later throw+// cannot take back what was proven; it is only told, and never changes a request, an answer or what is thrown.+async function publishTargets(provision, runner, concurrency, entityTargets, appTarget, warn, { keepGoing = false, checked = false, onProven = null } = {}) {const labelOf = targetLabel;+ const report = (result, label) => reportTablePush(result, label, warn, checked);const publishOne = async ([type, id], label) => {- if (!keepGoing) return reportPartialPush(await provision.publishArtifact(type, id), label, warn);+ if (!keepGoing) return report(await provision.publishArtifact(type, id), label);try {- return reportPartialPush(await provision.publishArtifact(type, id), label, warn);+ return report(await provision.publishArtifact(type, id), label);} catch (e) {- if (typeof warn === 'function') warn(`publish ${label} FAILED: ${(e && e.message) || e} — the change is SAVED but the runtime still serves the previously published copy; the build is idempotent, so re-run it once the cause is cleared`);+ const why = checked ? serviceAnswerText(publishFailureFacts(e)) : (e && e.message) || e;+ if (typeof warn === 'function') warn(`publish ${label} FAILED: ${why} — the change is SAVED but the runtime still serves the previously published copy; the build is idempotent, so re-run it once the cause is cleared`);return undefined;}};@@ -3249,9 +3263,22 @@ async function publishTargets(provision, runner, concurrency, entityTargets, app// would confirm it was not possible. An outcome that says nothing about publishing proves nothing.const published = (result) => !!(result && result.publish && result.publish.kind && result.publish.kind !== 'failed' && result.publish.kind !== 'notRequested');const refused = (result) => !!(result && result.publish && result.publish.kind === 'failed');+ // The proof publishedTargets collects, which is NOT `published` above: only a kind that says the request was sent and answered success+ // (managed-feature-contract.js publishAnswerProvesPublication: submitted, verified, unverifiable). `published` also passes `none`,+ // `notApplicable` (a result the real SDK gives with no request sent) and any unknown kind (which proves nothing either way), and stays+ // as it is for appPublished.+ const { publishAnswerProvesPublication: proves } = require('./managed-feature-contract.js');const failed = [];+ const publishedTargets = [];const all = appTarget ? [...entityTargets, appTarget] : entityTargets;const isApp = (target) => !!appTarget && target[0] === 'app' && target[1] === appTarget[1];+ const answers = new Map();+ // Each table target whose answer proves its publication, told as it is received: a later target (or the retry of one) that THROWS ends+ // this call before it returns anything, and must not take back what was already proven (createTablePublication). Told once per target,+ // only when it proves (a refused, a notApplicable or a missing answer is never told), and the app never.+ const prove = (target, outcome) => {+ if (typeof onProven === 'function' && !isApp(target) && !refused(outcome) && proves(outcome)) onProven(target, outcome);+ };if (all.length > 1 && typeof provision.publishArtifacts === 'function') {let results = null;try {@@ -3265,25 +3292,37 @@ async function publishTargets(provision, runner, concurrency, entityTargets, appresults.forEach((outcome, i) => {if (refused(outcome)) retry.push(all[i]);else {- reportPartialPush(outcome, labelOf(all[i]), warn);+ report(outcome, labelOf(all[i]));+ answers.set(all[i], outcome);+ prove(all[i], outcome);if (isApp(all[i])) appResult = outcome;+ else if (proves(outcome)) publishedTargets.push(all[i]);}});for (const target of retry) {const retried = await publishOne(target, labelOf(target));+ answers.set(target, retried);+ prove(target, retried);if (isApp(target)) appResult = retried;else if (refused(retried)) failed.push({ target, error: retried.publish.error });+ else if (proves(retried)) publishedTargets.push(target);}- return { appPublished: published(appResult), appResult, failed };+ return { appPublished: published(appResult), appResult, failed, publishedTargets, answers };}}- const outcomes = await runner.mapLimit(entityTargets, concurrency, (async (target) => publishOne(target, labelOf(target))));+ const outcomes = await runner.mapLimit(entityTargets, concurrency, (async (target) => {+ const outcome = await publishOne(target, labelOf(target));+ prove(target, outcome);+ return outcome;+ }));entityTargets.forEach((target, i) => {const outcome = (outcomes || [])[i];+ answers.set(target, outcome);if (refused(outcome)) failed.push({ target, error: outcome.publish.error });+ else if (proves(outcome)) publishedTargets.push(target);});const appResult = appTarget ? await publishOne(['app', appTarget[1]], appTarget[2]) : undefined;- return { appPublished: published(appResult), appResult, failed };+ return { appPublished: published(appResult), appResult, failed, publishedTargets, answers };}// What a publish target is FOR, in the words a warning or a halt prints: the names the target carries (a table's@@ -3292,14 +3331,126 @@ function targetLabel([type, id, label]) {return (Array.isArray(label) ? label.join(', ') : label) || `${type} ${id}`;}+// The checked facts of a publication the SDK refused, for a build with commandStates (lib/command-state-contract.js serviceAnswerText). The+// SDK answers a refused PublishXml BY VALUE ({ kind: 'failed', error }), its error made by the vendored SDK as, e.g.:+// { name: 'ConnectionError', code: 'CONNECTION_ERROR', statusCode: 503, url: 'https://contoso.crm.dynamics.com/api/data/v9.2/PublishXml',+// message: 'HTTP 503 from https://contoso.crm.dynamics.com/api/data/v9.2/PublishXml: <the service's text>',+// cause: { error: { code: '0x80040220', message: '<the service's text>' } } }+// and a transport that got no answer as { code: 'CONNECTION_ERROR', statusCode: 0, message: 'Transport failure reaching …: <text>' }.+// Only the status (an HTTP status, 100-599), the Dataverse code and the error's own code are taken, and serviceAnswerText checks each again+// (a 0x code, an upper-case system code); no message is, since every one of them can carry the service's text.+function publishFailureFacts(error) {+ const e = error && typeof error === 'object' ? error : {};+ const status = [e.statusCode, e.status].find((s) => Number.isInteger(s) && s >= 100 && s <= 599);+ const body = e.cause && typeof e.cause === 'object' && e.cause.error && typeof e.cause.error === 'object' ? e.cause.error : {};+ return {+ problem: 'publish-refused',+ ...(status ? { status } : {}),+ ...(typeof body.code === 'string' ? { dataverseCode: body.code } : {}),+ ...(typeof e.code === 'string' ? { systemCode: e.code } : {}),+ };+}++// reportPartialPush for a publication, worded for the build it runs in. `checked` (a build with commandStates): a failed publish is said by+// its checked facts (publishFailureFacts), and one whose read-back could not confirm it by a fixed reason, since the SDK's reason can quote+// the service (e.g. `the publish step failed: <its message>`). The answer handed back is the SDK's own, untouched: what decides a retry, an+// app's proof or a halt reads its structured error. Without `checked` this IS reportPartialPush, so a build without commandStates prints+// what 2.23.0 printed.+function reportTablePush(result, label, warn, checked) {+ if (!checked || !result || !result.publish || (result.publish.kind !== 'failed' && result.publish.kind !== 'unverifiable')) return reportPartialPush(result, label, warn);+ const publish = result.publish.kind === 'failed'+ ? { kind: 'failed', error: { message: serviceAnswerText(publishFailureFacts(result.publish.error)) } }+ : { kind: 'unverifiable', reason: 'the published layer was not read back' };+ reportPartialPush({ ...result, publish }, label, warn);+ return result;+}++// ONE way the build publishes a table, and tells commandStates' observer (lib/command-state-run.js createCommandStatePublicationObserver)+// what it published, so a table publication can no longer be added that the observer never hears about: every PublishXml of+// sdk-build.js that can name a table goes through a member of this (the contract test in command-state-publication-build.test.js reads+// this file and fails on one that does not; only the app's own publish, whose request names no table, is outside it).+// plain a PublishXml that names the tables (table-publish.js publishTablesXml): the envelope before the app+// managed the managed publisher's flush (managed-scope-publisher.js): one table's PublishXml each, `published` named; on a halt, what it+// settled before it (`onHalt`)+// sdk publishTargets: one artifact per table, in one envelope when the SDK offers it, and the app+// one the SDK's publish of one artifact (a reconcile, the app publication's table scope, when no publish phase follows)+// Only a publication whose request named the table confirms it (the design: a real publication of the table after its latest row write).+// For the SDK that is an answer of a kind that proves the request was sent and answered (managed-feature-contract.js+// publishAnswerProvesPublication) whose `publishScope` is the table's own entity envelope. The vendored SDK, run over a fake transport,+// sends a view's, a chart's, a form's and a table-bound dashboard's publish as `<entities><entity>t</entity></entities>` and answers+// `publishScope: { envelope: 'entity', entityLogicalName: 't' }`, also for each artifact of one batch; an unbound dashboard's as+// `<dashboards>` (envelope 'dashboard') and the app's as `<appmodules>` (envelope 'appmodule'), which name no table and confirm none.+//+// `observer` is null for a build without commandStates (and for a dry run): then nothing is told, and every request and every line is the+// one 2.23.0 made. With it (or with `checked`, which settleOwedPublishes passes after the build's proof is over), every line about a failed+// publication is said by its checked facts (lib/command-state-contract.js+// serviceAnswerText), never the service's text. `observed` names the call site in the observer's snapshot (`path`). The observer only+// records; what it does or throws never changes a publication or a halt.+function createTablePublication({ observer = null, checked = !!observer, provision, runner, concurrency = 1, managedTables = null, warn } = {}) {+ const tell = (fn) => {+ if (!observer) return;+ try { fn(observer); } catch { /* told only */ }+ };+ const lc = (value) => String(value || '').toLowerCase();+ const names = (answer, table) => {+ if (!table || !answer || !answer.publishScope) return false;+ const { publishAnswerProvesPublication: proves } = require('./managed-feature-contract.js');+ return proves(answer) && answer.publishScope.envelope === 'entity' && lc(answer.publishScope.entityLogicalName) === lc(table);+ };+ const sayRefusal = (outcome) => serviceAnswerText({ problem: 'publish-refused', ...((outcome && outcome.facts) || {}) });+ // An error a publication THROWS (the SDK's preflight of an artifact its workspace does not hold, a provider, a callback) is thrown on as+ // it is; with `checked` it carries, beside it, the checked words the halt says of it instead of its message (command-state-contract.js+ // withCheckedDisplay). A BuildHalt is the build's own words already (a throttle budget's stop), and is left as it is.+ const thrown = async (fn) => {+ if (!checked) return fn();+ try {+ return await fn();+ } catch (e) {+ if (!(e && e.name === 'BuildHalt')) withCheckedDisplay(e, serviceAnswerText(publishFailureFacts(e)));+ throw e;+ }+ };+ return {+ checked,+ async plain(client, tables, { observed = 'plain-before-app' } = {}) {+ const outcome = await publishTablesXml(client, tables, checked ? { facts: true } : undefined);+ tell((o) => o.observePlain(tables, outcome, observed));+ return outcome;+ },+ async managed(tables, { phase, path, observed = 'managed-before-app' } = {}) {+ const flushed = await managedTables.flush(tables, {+ phase, path, ...(checked ? { onHalt: (partial) => tell((o) => o.observeManaged(partial, observed)), sayRefusal } : {}),+ });+ tell((o) => o.observeManaged(flushed, observed));+ return flushed;+ },+ async sdk(targets, appTarget, { tableOf = () => null, observed = 'sdk-before-app', keepGoing = false } = {}) {+ // Each table is told as its answer proves it (publishTargets' onProven), not once the call returns: a later target that throws+ // ends the call, and the tables already proven stay told.+ const onProven = (target, answer) => {+ const table = tableOf(target);+ if (names(answer, table)) tell((o) => o.observeSdk([table], observed));+ };+ return thrown(() => publishTargets(provision, runner, concurrency, targets, appTarget, warn, { keepGoing, checked, onProven }));+ },+ async one(type, id, table, label, { observed } = {}) {+ const answer = reportTablePush(await thrown(() => provision.publishArtifact(type, id)), label, warn, checked);+ if (names(answer, table)) tell((o) => o.observeSdk([table], observed));+ return answer;+ },+ };+}+// The halt for tables whose publish was refused before the app was written. `failed` is publishTargets' `{ target, error }` per table. The message names the saved artifacts, which are the maker's (a// view called "SQL Timeout Reader"), and the service's answer to each. What decides whether a run again can help is each refusal's own structure — its status, its type, whether it says it must not be run// again — never the names: it is run again for a 429 or a 503 (the build re-runs a throttled publish as it did before this publish moved ahead of the app), and NEVER when any one table's refusal is final,// since the run would stop at that table again. The words that may decide are the answers' own (`retryText`, cut of the url each carries), never the names. The runner wraps this halt once more-// (makeRunner); the policy, the status and the words are read through that wrapper.-function reconciledPublishHalt(failed) {+// (makeRunner); the policy, the status and the words are read through that wrapper. `checked` (a build with commandStates): the message+// says each refusal by its checked facts (publishFailureFacts), never the service's text; the cause, the policy, the status and the words+// that decide a retry are the same.+function reconciledPublishHalt(failed, { checked = false } = {}) {const names = failed.map(({ target }) => targetLabel(target)).join('; ');- const detail = failed.map(({ error }) => (error && error.message) || 'refused').join('; ');+ const detail = failed.map(({ error }) => (checked ? serviceAnswerText(publishFailureFacts(error)) : (error && error.message) || 'refused')).join('; ');const errors = failed.map(({ error }) => error);const final = errors.some((error) => retryPolicyFor(error) === RETRY.NEVER);const status = errors.map((error) => error && (error.statusCode || error.status)).find(isTransientStatus);@@ -3340,21 +3491,27 @@ function reconciledPublishHalt(failed) {// could not be read, and which tables to publish. It is read AFTER the publishes, so what they made live is not claimed, and only for// forms, views and charts (table-publish.js): a column or command saved and not published is not covered, and the line says so. Without// `tables`, as the CLI passes none for a dry run or a build with no publish phase, nothing is read.-async function settleOwedPublishes(provision, owed, warn, { tables } = {}) {+// `checked`: the halted build declared commandStates (build-model-app.js passes it when the run made the feature's observer), so a failed+// publish here is said by its checked facts too (createTablePublication), and so is a failed read of what is still saved and not published+// (describeSavedNotPublished `checked`); nothing is observed, since the build's proof is over.+async function settleOwedPublishes(provision, owed, warn, { tables, checked = false } = {}) {const targets = Array.isArray(owed) ? owed.filter((target) => Array.isArray(target) && target[0] && target[1]) : [];const say = (message) => { if (typeof warn === 'function') warn(`the build stopped before its publish phase; ${message}`); };if (provision && targets.length) {try {- await publishTargets(provision, makeRunner({ emit: () => undefined, total: 0 }), 1, targets, null, say, { keepGoing: true });+ const settle = createTablePublication({ observer: null, provision, runner: makeRunner({ emit: () => undefined, total: 0 }), concurrency: 1, warn: say, checked });+ await settle.sdk(targets, null, { keepGoing: true });} catch (e) {- say(`publishing the views and forms it had already saved FAILED: ${(e && e.message) || e} — the change is SAVED but the runtime still serves the previously published copy; the build is idempotent, so re-run it once the cause is cleared`);+ say(`publishing the views and forms it had already saved FAILED: ${checked ? serviceAnswerText(publishFailureFacts(e)) : (e && e.message) || e} — the change is SAVED but the runtime still serves the previously published copy; the build is idempotent, so re-run it once the cause is cleared`);}}// An SDK with no raw client to read with is a test double: the real one always has it, so there is nothing to say about its absence.const client = provision && provision.dataverse;if (typeof warn !== 'function' || !Array.isArray(tables) || !tables.length || !client || typeof client.get !== 'function') return;try {- const text = describeSavedNotPublished(await readSavedNotPublished(client, tables), tables);+ const text = checked+ ? describeSavedNotPublished(await readSavedNotPublished(client, tables, { facts: true }), tables, { checked: true })+ : describeSavedNotPublished(await readSavedNotPublished(client, tables), tables);if (text) say(text);} catch { /* the halt is what the operator must see; a report on what else is not live never hides it */ }}@@ -3449,6 +3606,10 @@ function protectedConfigurationFor(gate, store, { env, approvals } = {}) {// second apply of the same app in the same workspace is refused before anything is read or written, so two builds cannot both find the app's icon,// the app or a page missing and both create it. A dry run reads only, and takes no lease.async function runSdkBuild(spec, opts = {}) {+ // commandStates (lib/command-state-run.js commandStateSpecHalt): checked here, at the engine's public entry, before the lease, the mode+ // choice or any request, so a direct caller gets the same refusal as the CLI and a bad value is never read as absent.+ const commandStateSpecError = commandStateSpecHalt(spec);+ if (commandStateSpecError) throw commandStateSpecError;if (!opts.apply) return runSdkBuildAttempt(spec, opts);return withAppBuildLease({ workspaceDir: applyWorkspaceOf(opts), appUniqueName: appUniqueName(spec), buildLease: opts.buildLease, warn: opts.warn }, () => runSdkBuildAttempt(spec, opts));}@@ -3470,6 +3631,9 @@ async function runSdkBuildAttempt(spec, opts = {}) {// (oweTablePublish). lengths: table logical -> { table, column, asked, tried, tableId, columnId? } of a name column whose// length is owed.const owed = { tables: new Map(), paid: false, lengths: new Map(), barrier: opts.publicationBarrier || createPublicationBarrier() };+ // commandStates (lib/command-state-run.js): whether this invocation's table publication covered each table a command row was written on is+ // recorded by one observer for the whole invocation — build-model-app.js hands every attempt the same one; a direct caller's attempt makes its own.+ owed.commandStateObserver = commandStateModeOf(spec, opts).mode === 'apply' ? (opts.commandStateObserver || createCommandStatePublicationObserver()) : null;// A record this attempt was handed is a debt it has not tried to pay yet, whatever an earlier attempt did with it.let carriedIn = 0;for (const debt of Array.isArray(opts.owedLengths) ? opts.owedLengths : []) {@@ -3493,10 +3657,41 @@ async function runSdkBuildAttempt(spec, opts = {}) {Object.defineProperty(err, 'owedLengths', { value: [...owed.lengths.values()], enumerable: false, configurable: true, writable: true });} catch { /* a frozen error carries nothing; a run that finds the table leaves its name column as it is, which the warning said */ }}+ // What the halt leaves of the command states: the rows' results and, while a declared table is not seen published, why (not enumerable).+ if (owed.commandStateObserver) owed.commandStateObserver.attachFailure(err);throw err;}}+// How this run treats the spec's commandStates (lib/command-state-run.js commandStateMode): the changed-only fast path is never a full apply.+function commandStateModeOf(spec, opts) {+ return commandStateMode(spec, { apply: !!opts.apply, publish: !!opts.publish, phases: opts.phases || PHASES, changedOnlyFast: !!(opts.changedOnly && opts.changedOnly.fastApply) });+}++// The command rows' reader and writer: the caller's own (a test), or one over the raw client build-model-app.js made for command rows alone (its+// row PATCH is never resent: commandStateSendOnce), rooted at the SDK's API root. Null when there is none: the run then stops before it reads.+function commandStateTransportFor(opts, sdk) {+ if (opts.commandStateTransport) return opts.commandStateTransport;+ if (!opts.commandStateClient) return null;+ try {+ return createCommandStateTransport({ client: opts.commandStateClient, apiUrl: (path) => sdk.dataverse.apiUrl(path) });+ } catch {+ return null;+ }+}++// A dry run's command states: read-only, and only with the commands phase. A live plan reads every row and prints the exact approvals an apply+// would need; a plan asked not to read the environment (or with no reader) says the rows are unverified and prints no token. A row the live plan+// cannot plan stops the dry run (exit 1): an approval printed for a row that cannot be written would be a token for nothing.+async function planCommandStatesForDryRun(spec, opts, sdk, has) {+ if (commandStateModeOf(spec, opts).mode === 'off') return undefined;+ if (!has('commands')) return { status: 'skipped', reason: 'the commands phase is not selected: command states are neither read nor applied' };+ const transport = opts.livePlan === false ? null : commandStateTransportFor(opts, sdk);+ if (!transport) return { status: 'unverified', reason: 'the rows were not read (offline plan), so no approval token is printed; run a live dry run for them' };+ const run = createCommandStateRun({ spec, transport, origin: opts.env, approvals: opts.commandStateApprovals, publish: true });+ return { status: 'planned', ...(await run.plan()) };+}+// A run with sample data and without the data-model phase (`--phases sample-data`) never secures a column: the data-model phase does that,// before any row is written. So before such a run seeds a table with a column the spec declares `isSecured: true`, it reads, once per// seeded table, whether that column is secured now, and stops before the first row when it is not, or when the read cannot say. Without@@ -3668,6 +3863,7 @@ async function runSdkBuildPhases(spec, opts, owed) {preview = { ok: false, allEvaluated: false, error: findingOf(err, 'PREVIEW_FAILED') };}}+ const commandStatePlan = await planCommandStatesForDryRun(spec, opts, provision, has);return {ok: true,dryRun: true,@@ -3676,9 +3872,20 @@ async function runSdkBuildPhases(spec, opts, owed) {planItems: plan.map((p) => ({ phase: p.phase, label: p.label, ...(p.state ? { state: p.state } : {}), ...(p.stateWhy ? { stateWhy: p.stateWhy } : {}), ...(p.wouldHalt ? { wouldHalt: true } : {}),...(p.op ? { op: p.op, destructive: p.destructive, description: p.description, publication: p.publication } : {}) })),...(preview ? { pushPreview: preview } : {}),+ ...(commandStatePlan ? { commandStatePlan } : {}),};}+ // commandStates: a partial apply, an apply without --publish, or one with keyed commands[] is refused here, before anything is read or written.+ // Exactly --stage data leaves the rows alone (no read, no approval) and says so.+ const commandStateModeOfRun = commandStateModeOf(spec, opts);+ if (commandStateModeOfRun.mode === 'error') {+ throw new BuildHalt(`${commandStateModeOfRun.code}: ${commandStateModeOfRun.message}`, { phase: 'preflight', code: commandStateModeOfRun.code, recoverable: false, retry: RETRY.NEVER });+ }+ if (commandStateModeOfRun.mode === 'data-stage' && typeof opts.warn === 'function') {+ opts.warn('commandStates: not applied by --stage data (no command row is read or written); a full build with --publish applies them');+ }+// Capture the attempt's checkpoint before best-effort preflight reads can swallow a refused throttle wait as unchecked metadata. The same runner then stops before any mutation, without counting refusals from earlier attempts.const runner = makeRunner({ emit, total: plan.length, throttle: opts.throttle });// A navigation Dataverse will refuse stops the build here, before anything is written, rather than at the app step@@ -4164,6 +4371,8 @@ async function runSdkBuildPhases(spec, opts, owed) {const managedTables = bindingGroups && bindingGroups.store && provision.dataverse? require('./managed-scope-publisher.js').createManagedTablePublisher({ store: bindingGroups.store, barrier: owed.barrier, client: provision.dataverse, halt: managedStop, settle: opts.publicationSettle }): null;+ // Every table publication of the build below goes through this (createTablePublication), so the commandStates observer hears of each.+ const tablePublication = createTablePublication({ observer: owed.commandStateObserver, provision, runner, concurrency, managedTables, warn: opts.warn });if (managedTables) await retireAbsentRemovedForms();// haltOnUnconfirmedRetirements: a dashboard or form retirement the sweeps above could not confirm ends this invocation// here. Both sweeps run before the first service write of the attempt (everything above only reads), so this attempt@@ -4217,6 +4426,12 @@ async function runSdkBuildPhases(spec, opts, owed) {// still stops on an attempt an earlier build left unfinished (sweepPendingConfiguration), whatever phases this run selects.if (configurationRun) await configurationRun.preflight();else sweepPendingConfiguration(spec, configurationOpts);+ // commandStates (lib/command-state-run.js), before the first write too: every declared row read and judged and every approval present, or+ // the build stops having written nothing. Only a full apply with --publish gets here with a run (commandStateModeOf, above).+ const commandStateRun = commandStateModeOfRun.mode === 'apply'+ ? createCommandStateRun({ spec, transport: commandStateTransportFor(opts, provision), origin: opts.env, approvals: opts.commandStateApprovals, publish: true, observer: owed.commandStateObserver })+ : null;+ if (commandStateRun) await commandStateRun.preflight();// The web resources an earlier run of this build wrote and could not confirm were published (lib/web-resource-records.js), read at first use: the// spec's web resources and the generated app icon are written again by id when they are in it, and the page manifest is written again by its id where// its published copy is not what the run wants (kept where it is: persistPageManifest). One per run of the phases, so the@@ -4333,7 +4548,7 @@ async function runSdkBuildPhases(spec, opts, owed) {// refusal below remembers it as wanted).if (logical && isRouted(logical)) {owed.barrier.allow(logical, label);- if (!publishInPhase8) await managedTables.flush([logical], { phase: 'publish', path: label });+ if (!publishInPhase8) await tablePublication.managed([logical], { phase: 'publish', path: label, observed: 'managed-reconcile' });return;}if (logical && !owed.barrier.allow(logical, label)) return;@@ -4342,7 +4557,7 @@ async function runSdkBuildPhases(spec, opts, owed) {reconciledTables.add(logical);return;}- reportPartialPush(await provision.publishArtifact(type, id), label, opts.warn);+ await tablePublication.one(type, id, logical, label, { observed: 'sdk-reconcile' });};// Drain what settlement scheduled onto the build's own queues. `charts` is the charts phase's chartsToPublish;// the views phase passes nothing (a chart scope cannot be settled there).@@ -4377,16 +4592,23 @@ async function runSdkBuildPhases(spec, opts, owed) {// This is the SDK's publish of the reconciled tables: publishTablesBeforeApp sends them by name, with the other tables it publishes before the// app, when it can, and comes here when that request is refused and when there is no raw client.const publishReconciledTables = async () => {- const targets = [...reconciledTables].filter((l) => owed.barrier.allow(l, 'tables published before the app')).map((logical) => owed.tables.get(logical)).filter(Boolean);+ const logicals = [...reconciledTables].filter((l) => owed.barrier.allow(l, 'tables published before the app'));+ const targets = logicals.map((logical) => owed.tables.get(logical)).filter(Boolean);reconciledTables.clear();if (!targets.length) return;- const { failed } = await publishTargets(provision, runner, concurrency, targets, null, opts.warn);+ // commandStates (lib/command-state-run.js): a table this SDK publication proved published, by a request that named it, is a publication+ // of the table after its command-row writes (the commands phase sends them all before any app write, and a later write would undo the+ // confirmation: noteRowWrite), so createTablePublication tells the observer — the refused envelope that sent the table here recorded only+ // `failed`, and the table is not named again before the app (namedBeforeApp). A table it reports refused, or answered with a no-request+ // kind (`notApplicable`, `none`, `notRequested`), an unknown kind, nothing, or a publishScope that is not the table's, stays as it was.+ const tableOf = (target) => logicals.find((logical) => owed.tables.get(logical) === target) || null;+ const { failed } = await tablePublication.sdk(targets, null, { tableOf, observed: 'sdk-before-app' });if (!failed.length) return;// A table whose publish the SDK refused (by value: it never throws for one) still holds its saved labels// unpublished, and the app's publish below would strand them for good — so the build stops before it writes the// app. Nothing is lost: the halt carries every table this run owes (runSdkBuild), the CLI re-runs a transient// refusal at once, and once no retry follows it publishes them without the app (settleOwedPublishes).- throw reconciledPublishHalt(failed);+ throw reconciledPublishHalt(failed, { checked: tablePublication.checked });};// ...and the tables the app is PROVEN to hold a form or chart of, and the charts this run wrote. The measured strand follows from the order of the@@ -4472,19 +4694,33 @@ async function runSdkBuildPhases(spec, opts, owed) {const verdict = owed.barrier.checkAppWrite({ added, held: appHolds.unread ? undefined : [...(appHolds.tables || []), ...appAdded], existingApp: !!existingAppId, addedDashboards: Object.values(result.created.dashboards || {}).filter(Boolean) });if (!verdict.ok) throw new BuildHalt(describeWithheldApp(verdict), { phase: 'app-shell', code: 'publication-withheld', recoverable: true, retry: RETRY.NEVER });}+ // commandStates (lib/command-state-run.js): the observer only records what this path answers; it sends nothing and never throws.+ const commandStateObserver = owed.commandStateObserver;+ // The managed publisher's share of this envelope. It publishes one routed table at a time and throws on the first it cannot, so+ // the tables it published before that halt reach the observer through `onHalt` (managed-scope-publisher.js flush, which+ // createTablePublication hands it): a table it confirmed is reported confirmed and the failing one `failed`, never+ // `halted-before-send`. The halt itself is thrown as it was.+ const flushManaged = async () => {+ await tablePublication.managed(owed.barrier.routedWanted(), { phase: 'app-shell', path: 'tables published before the app', observed: 'managed-before-app' });+ };if (!publish || !client || typeof client.post !== 'function') {for (const logical of added || []) appAdded.add(logical);await publishReconciledTables();- if (managedTables) await managedTables.flush(owed.barrier.routedWanted(), { phase: 'app-shell', path: 'tables published before the app' });+ if (managedTables) await flushManaged();return undefined;}await readHoldings();for (const logical of added) appAdded.add(logical);- const wanted = owed.barrier.allowTables(preAppTables({ reconciled, charted: [...chartsToPublish.keys()], added, held: appHolds.tables }), 'tables published before the app');+ const preApp = preAppTables({ reconciled, charted: [...chartsToPublish.keys()], added, held: appHolds.tables });+ // A table whose command row the build edits is published in the same envelope, before the app: its rows are served once it is.+ const askedBeforeApp = commandStateObserver ? [...new Set([...preApp, ...commandStateObserver.declaredTables()])].sort() : preApp;+ const wanted = owed.barrier.allowTables(askedBeforeApp, 'tables published before the app');// A routed table is left out of the request above and remembered as wanted: the managed publisher sends it first.- if (managedTables) await managedTables.flush(owed.barrier.routedWanted(), { phase: 'app-shell', path: 'tables published before the app' });+ if (managedTables) await flushManaged();const tables = wanted.filter((logical) => !namedBeforeApp.has(logical));- const outcome = await publishTablesXml(client, tables);+ // With commandStates the failure is asked for its checked facts too (createTablePublication): its warning below must not quote the+ // platform's text. Only a non-empty list answered ok confirms, and only the names it carried (an empty list answers ok without a request).+ const outcome = await tablePublication.plain(client, tables, { observed: 'plain-before-app' });for (const logical of tables) namedBeforeApp.add(logical);if (outcome.ok) {reconciledTables.clear();@@ -4493,7 +4729,11 @@ async function runSdkBuildPhases(spec, opts, owed) {await publishReconciledTables();const unprotected = tables.filter((logical) => !reconciled.has(logical));if (unprotected.length && typeof opts.warn === 'function') {- opts.warn(describePreAppRefusal({ reason: outcome.reason, tables: unprotected, saved: savedOnTable, described: describedCharts, forms: appHolds.forms, added }));+ // A build with commandStates says the refusal by its checked facts only (lib/command-state-contract.js serviceAnswerText): the+ // platform's text can carry a row version or anything else, and this feature lets none of it into what the build prints.+ // Without commandStates the warning quotes the reason as it always did.+ const reason = commandStateObserver ? serviceAnswerText({ problem: 'publish-refused', ...(outcome.facts || {}) }) : outcome.reason;+ opts.warn(describePreAppRefusal({ reason, tables: unprotected, saved: savedOnTable, described: describedCharts, forms: appHolds.forms, added }));}return undefined;});@@ -4632,7 +4872,7 @@ async function runSdkBuildPhases(spec, opts, owed) {owed.barrier.allow(logical, label);const failed = (error) => ({ type: target.artifact.type, id: target.artifact.id, shipped: false, publish: { kind: 'failed', error } });try {- const out = await managedTables.flush([logical], { phase: 'publish', path: label });+ const out = await tablePublication.managed([logical], { phase: 'publish', path: label, observed: 'managed-app-publication' });if (out.withheld.includes(logical)) return failed({ code: 'publication-withheld', message: `the publish of table ${target.id} is withheld in this run` });return { type: target.artifact.type, id: target.artifact.id, shipped: true, publish: { kind: 'submitted' } };} catch (err) {@@ -4643,7 +4883,7 @@ async function runSdkBuildPhases(spec, opts, owed) {if (!owed.barrier.allow(String(target.id).toLowerCase(), label)) {return { type: target.artifact.type, id: target.artifact.id, shipped: false, publish: { kind: 'failed', error: { code: 'publication-withheld', message: `the publish of table ${target.id} is withheld in this run` } } };}- return reportPartialPush(await provision.publishArtifact(target.artifact.type, target.artifact.id), label, opts.warn);+ return tablePublication.one(target.artifact.type, target.artifact.id, logical, label, { observed: 'sdk-app-publication' });},},},@@ -7056,7 +7296,7 @@ async function runSdkBuildPhases(spec, opts, owed) {phase: 'views', client: provision.dataverse, halt: managedStop, warn: opts.warn, authorizedAdoption: featureCtx.authorizedAdoption,ensureMember: (kind, id, table) => ensureInSolution(id, COMPONENT_TYPE[kind], table),});- if (tables.length && managedTables) await managedTables.flush(tables, { phase: 'views', path: 'recovered change of an undeclared view or chart' });+ if (tables.length && managedTables) await tablePublication.managed(tables, { phase: 'views', path: 'recovered change of an undeclared view or chart', observed: 'managed-views-phase' });}// 4. Views (independent -> parallel).@@ -7143,7 +7383,7 @@ async function runSdkBuildPhases(spec, opts, owed) {throw marked(err);}// A routed table is held above; the managed publisher publishes it in place of the SDK.- if (isRouted(logical)) await managedTables.flush([logical], { phase: 'views', path: `default views of ${logical}` });+ if (isRouted(logical)) await tablePublication.managed([logical], { phase: 'views', path: `default views of ${logical}`, observed: 'managed-views-phase' });return updated;}try {@@ -8552,6 +8792,9 @@ async function runSdkBuildPhases(spec, opts, owed) {}if (has('commands')) {+ // commandStates: everything read again before the first row write; a row that changed since its approval stops the build here.+ if (commandStateRun) await commandStateRun.recheckAll();+ const commandStateTables = new Set(commandStateRun ? commandStateRun.requiredTables() : []);for (const [entityLogical, cmds] of Object.entries(commandsByEntity(spec))) {if (isManagedEntity(cmds)) {// A keyed command bar (commands[].key, lib/command-reconcile.js): one fetch, a push only when something changed.@@ -8576,6 +8819,12 @@ async function runSdkBuildPhases(spec, opts, owed) {result.created.commands[entityLogical] = existingId;continue;}+ // A new command bar on a table whose existing buttons commandStates edits in the same build: refused before it is created, so one build+ // never both creates buttons on a table and edits that table's rows (the state rows were judged before the bar existed).+ if (commandStateTables.has(String(entityLogical).toLowerCase())) {+ throw new BuildHalt(`${COMMAND_STATE_CODES.legacyCreateConflict}: commands[] for ${entityLogical}: ${COMMAND_STATE_REMEDY[COMMAND_STATE_CODES.legacyCreateConflict]}`,+ { phase: 'commands', code: COMMAND_STATE_CODES.legacyCreateConflict, recoverable: false, retry: RETRY.NEVER });+ }await runner.run('commands', `command bar for ${entityLogical} (${cmds.length} button(s))`, async () => {const def = commandDef(entityLogical, cmds, result.created.webResources);const art = await provision.createArtifact('command', def);@@ -8583,6 +8832,8 @@ async function runSdkBuildPhases(spec, opts, owed) {result.created.commands[entityLogical] = pushed.id;});}+ // Then the rows, one at a time, before the commands phase ends: the before-app table publication that follows covers them.+ if (commandStateRun) await commandStateRun.applyRows();}// 6c. Dashboards. createArtifact('dashboard') seeds a dashboard; each chart/list/iframe/webresource@@ -10707,7 +10958,7 @@ async function runSdkBuildPhases(spec, opts, owed) {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);if (asked) ask.push(k);}- managedOut = await managedTables.flush(ask, { phase: 'publish', path: 'publish customizations' });+ managedOut = await tablePublication.managed(ask, { phase: 'publish', path: 'publish customizations', observed: 'managed-publish-phase' });}const perEntity = []; // [type, id, names?] — first artifact found per entity// The table's target carries the names of what its one publish ships: what was deferred onto it (its reconciled views@@ -10761,7 +11012,8 @@ async function runSdkBuildPhases(spec, opts, owed) {}// A throw may come after the app's PublishXml reached the server (a lost answer): the app's exact proof is void.// A throw from a table publish before the app's was sent un-proves it too — conservative: the re-run proves it again.- const publishedTargets = await publishTargets(provision, runner, concurrency, perEntity, appWithheld ? null : appTarget, opts.warn).catch(async (error) => {+ // commandStates: each table this publish proved published, by a request that named it, is told to the observer (createTablePublication).+ const publishedTargets = await tablePublication.sdk(perEntity, appWithheld ? null : appTarget, { tableOf: (target) => tableOfTarget.get(target) || null, observed: 'sdk-publish-phase' }).catch(async (error) => {if (appTarget && !appWithheld) await appPublication.noteAppPublication(result.created.app, { error });throw error;});@@ -10933,7 +11185,7 @@ async function runSdkBuildPhases(spec, opts, owed) {const flushed = await appPublication.flush();// A routed table some plain publish of this run asked for and nothing paid yet is published now, once; one that cannot be// (no client to publish with) leaves the build incomplete, its debt kept in the store.- if (managedTables && owed.barrier.routedWanted().length) await managedTables.flush(owed.barrier.routedWanted(), { phase: 'publish', path: 'managed publication' });+ if (managedTables && owed.barrier.routedWanted().length) await tablePublication.managed(owed.barrier.routedWanted(), { phase: 'publish', path: 'managed publication', observed: 'managed-end-of-build' });for (const logical of owed.barrier.routedWanted()) markIncomplete({ phase: 'publish', code: 'managed-publication-owed', message: `table ${logical}: its publish is owed to the managed binding store and was not sent in this run; the change is saved, re-run the build to publish it` });// An app row is { id, code }; a scope row (a table) is { kind, id, code, reasons }.for (const { kind = 'app', id, code } of [...flushed.withheld, ...flushed.failed]) if (!(kind === 'table' && code === 'publication-withheld')) markIncomplete({ phase: 'publish', code, message: `${kind} ${id}: its publication is owed (${code}); the change is saved, re-run once the cause is cleared` });@@ -10970,7 +11222,13 @@ async function runSdkBuildPhases(spec, opts, owed) {Object.defineProperty(halt, 'incomplete', { value: incomplete, enumerable: false, configurable: true, writable: true });throw halt;}+ // commandStates, after all the shared work: every declared table's publication confirmed for its latest row write, or exit 1+ // (command-state-publish-unconfirmed). Its rows' results are on the result either way (the halt carries them: runSdkBuildAttempt).+ if (commandStateRun) {+ await commandStateRun.assertComplete();+ result.commandStates = commandStateRun.result();+ }return result;}-module.exports = { runSdkBuild, openBuildBindingGroups, protectedConfigurationInPlay, publishTargets, partialEnrichment, settleOwedPublishes, collectOwedPublishes, settleOwedLengths, normalizeFormId, planFor, annotateLivePlan, previewTargetOf, previewItemsForPlan, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, findPinnedDashboard, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, applyAppAiDescription, haltOnUnpublishedAppHeader, pushAppHeader, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, webResourceContentState, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause, roleGrantLabel, resolveRoleGrantTarget, existingAppSitemapIsWritten, pagesFirstRule, applyAppHeader, applyAppHeaderText, warnAppIconNotApplied, inspectBpfStages, applyBpfStages, refuseUnpushedAppCopy, assertAuthorizedSitemapRewrite, reconciledPublishHalt, COMMAND_DEFAULT_PARAMETERS };+module.exports = { runSdkBuild, openBuildBindingGroups, protectedConfigurationInPlay, publishTargets, createTablePublication, partialEnrichment, settleOwedPublishes, collectOwedPublishes, settleOwedLengths, normalizeFormId, planFor, annotateLivePlan, previewTargetOf, previewItemsForPlan, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, findPinnedDashboard, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, applyAppAiDescription, haltOnUnpublishedAppHeader, pushAppHeader, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, webResourceContentState, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause, roleGrantLabel, resolveRoleGrantTarget, existingAppSitemapIsWritten, pagesFirstRule, applyAppHeader, applyAppHeaderText, warnAppIconNotApplied, inspectBpfStages, applyBpfStages, refuseUnpushedAppCopy, assertAuthorizedSitemapRewrite, reconciledPublishHalt, COMMAND_DEFAULT_PARAMETERS };diff --git a/plugins/model-apps/scripts/lib/table-publish.js b/plugins/model-apps/scripts/lib/table-publish.jsindex 972ac9f84..ab85fd20a 100644--- a/plugins/model-apps/scripts/lib/table-publish.js+++ b/plugins/model-apps/scripts/lib/table-publish.js@@ -129,17 +129,22 @@ const tablesPublishXml = (names) => `<importexportxml><entities>${names.map((t)// client answers `{ status, body }` and does not throw on an HTTP error (lib/sdk-http-client.js); a transport failure does throw. The client// sends a publish once, so a refusal — the customization lock's 429 included — is reported as it came; a deadlock victim is sent again by// postPublishXml (lib/publish-xml.js). A refusal's platform text, when it gives one, is kept: `{ "error": { "code": "0x80040217", "message": "..." } }`.-async function publishTablesXml(client, tables, { sleep } = {}) {+// `facts: true` adds `facts` to a failure: the answer's status, its `error.code` and a thrown failure's `code`, as they came and UNCHECKED. A caller+// that must not print the platform's text (a build with commandStates) words the failure from them alone, through a formatter that checks each+// (lib/command-state-contract.js serviceAnswerText). Without it the answer is exactly what it always was.+async function publishTablesXml(client, tables, { sleep, facts = false } = {}) {const names = Array.isArray(tables) ? tables : [];if (!names.length) return { ok: true };- if (!client || typeof client.post !== 'function') return { ok: false, reason: 'no client to publish with' };+ const failed = (reason, answer) => (facts ? { ok: false, reason, facts: answer } : { ok: false, reason });+ if (!client || typeof client.post !== 'function') return failed('no client to publish with', {});try {const response = await postPublishXml(client, tablesPublishXml(names), { sleep });if (response && response.status >= 200 && response.status < 300) return { ok: true };- const said = response && response.body && response.body.error && response.body.error.message;- return { ok: false, reason: `PublishXml answered HTTP ${response && response.status}${typeof said === 'string' && said ? `: ${said}` : ''}` };+ const error = response && response.body && typeof response.body === 'object' ? response.body.error : undefined;+ const said = error && error.message;+ return failed(`PublishXml answered HTTP ${response && response.status}${typeof said === 'string' && said ? `: ${said}` : ''}`, { status: response && response.status, dataverseCode: error && error.code });} catch (e) {- return { ok: false, reason: (e && e.message) || String(e) };+ return failed((e && e.message) || String(e), { systemCode: e && e.code });}}@@ -196,27 +201,65 @@ const shown = (value) => (typeof value === 'string' ? `'${value.slice(0, 40)}'`// NO list: a partial one would read as the whole. A row the read cannot place is such an answer, not a record that is published: one that carries// no state, or a state that is none of the four, or no id (two records of one name would collapse into one), or no table (it may be the very one a// reader is asking about). The three collections are read one after the other, so a bad row in the last one makes the first one's list unreadable too.-async function readSavedNotPublished(client, tables) {+//+// `facts: true` adds `facts` to a failure, as publishTablesXml does, UNCHECKED: `read`, the label of the read that failed (`the saved views`),+// and what failed about it — the answer's status and its `error.code` (`problem: 'failed'`), a thrown failure's `code`, an answer that is not a+// list (`not-a-list`) or whose next-page link is not one (`malformed-link`), the field a row got wrong (`malformed-field`, `componentstate`), a+// row that cannot be placed (`unplaceable`), else `unexpected`. A caller that must not print the platform's text (a build with commandStates)+// says the failure from them alone (describeSavedNotPublished, `checked`). Without it the answer is exactly what it always was.+async function readSavedNotPublished(client, tables, { facts = false } = {}) {const wanted = [...new Set((Array.isArray(tables) ? tables : []).map((t) => String(t).toLowerCase()))];if (!wanted.length) return { ok: true, byTable: new Map() };- if (!client || typeof client.get !== 'function') return { ok: false, reason: 'no client to read with' };+ if (!client || typeof client.get !== 'function') return { ok: false, reason: 'no client to read with', ...(facts ? { facts: { problem: 'unexpected' } } : {}) };const found = new Map(wanted.map((table) => [table, new Map()]));+ // With `facts`, every answer the read gets is looked at as it comes (collectionRows makes its failures of the answer's text): the last one+ // that is not a usable page is what failed, and a thrown read is its own code.+ let reading = null;+ let failure = null;+ let reader = client;+ if (facts) {+ const look = (response) => {+ const body = response && response.body;+ if (!response || response.status < 200 || response.status >= 300) {+ const error = body && typeof body === 'object' && body.error && typeof body.error === 'object' ? body.error : {};+ failure = { problem: 'failed', status: response && response.status, dataverseCode: error.code };+ } else if (!body || !Array.isArray(body.value)) failure = { problem: 'not-a-list' };+ else if (body['@odata.nextLink'] !== undefined && (typeof body['@odata.nextLink'] !== 'string' || !body['@odata.nextLink'])) failure = { problem: 'malformed-link' };+ return response;+ };+ const asked = (fn) => async (...args) => {+ try {+ return look(await fn(...args));+ } catch (e) {+ failure = { problem: 'failed', systemCode: e && e.code };+ throw e;+ }+ };+ reader = { get: asked(client.get.bind(client)) };+ if (typeof client.getAbsolute === 'function') reader.getAbsolute = asked(client.getAbsolute.bind(client));+ if (typeof client.apiUrl === 'function') reader.apiUrl = client.apiUrl.bind(client);+ }try {for (const layer of LAYERED) {+ reading = layer.label;for (let start = 0; start < wanted.length; start += TABLES_PER_READ) {const filter = wanted.slice(start, start + TABLES_PER_READ).map((table) => `${layer.tableField} eq '${odataLit(table)}'`).join(' or ');- const rows = await collectionRows(client,+ failure = null;+ const rows = await collectionRows(reader,`/${layer.collection}/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=${layer.idField},name,${layer.tableField},componentstate&$filter=${filter}`,layer.label);for (const row of rows) {const state = row && row.componentstate;+ failure = { problem: 'malformed-field', field: 'componentstate' };if (state === undefined || state === null) throw new Error(`${layer.label}: the answer names no saved or published state (componentstate), so what is published cannot be told`);const code = stateOf(state);if (code === null) throw new Error(`${layer.label}: a record carries componentstate ${shown(state)}, which is not a saved or published state`);+ failure = { problem: 'unplaceable' };const tableValue = row[layer.tableField];if (typeof tableValue !== 'string' || !tableValue.trim()) throw new Error(`${layer.label}: a record has no ${layer.tableField}, so the table it belongs to cannot be told`);const idValue = row[layer.idField];if (typeof idValue !== 'string' || !idValue.trim()) throw new Error(`${layer.label}: a record has no ${layer.idField}, so it cannot be told from another`);+ failure = null;const table = tableValue.trim().toLowerCase();if (!found.has(table) || (code !== UNPUBLISHED && code !== DELETED_UNPUBLISHED)) continue;const id = idValue.trim().toLowerCase();@@ -226,7 +269,9 @@ async function readSavedNotPublished(client, tables) {}}} catch (e) {- return { ok: false, reason: clipReason((e && e.message) || e) };+ const reason = clipReason((e && e.message) || e);+ if (!facts) return { ok: false, reason };+ return { ok: false, reason, facts: { read: reading, ...(failure || { problem: 'unexpected' }) } };}const kindOrder = LAYERED.map((layer) => layer.kind);const byTable = new Map();@@ -281,12 +326,22 @@ const MAX_NAMES = 20;// The sentence a halted build adds when it stopped before its publish phase: what `read` found saved and not published on the spec's tables, or// — when it could not read — that it could not, with the tables to publish. `null` when there is nothing to say: nothing is saved and// unpublished. It names forms, views and charts only, and says so: a column or a command saved and not published is not read here.-function describeSavedNotPublished(read, tables) {+// `checked` (a build with commandStates): a read that failed is said by its checked facts (readSavedNotPublished `facts`, worded by+// command-state-contract.js serviceAnswerText): which read it was, by one of the three fixed labels, and what failed, never the platform's+// text. What a read that succeeded found is said the same either way: the names of the maker's own forms, views and charts.+function describeSavedNotPublished(read, tables, { checked = false } = {}) {if (!read) return null;const names = [...new Set((Array.isArray(tables) ? tables : []).map((t) => String(t)))];if (!read.ok) {if (!names.length) return null;- return `which forms, views and charts on the spec's tables are saved but not published could not be read (${read.reason}). Run the build again with --publish, or publish these tables in Power Apps: ${tableList(names, MAX_NAMES)}.`;+ let reason = read.reason;+ if (checked) {+ const { serviceAnswerText } = require('./command-state-contract.js');+ const { read: label, ...failure } = read.facts || { problem: 'unexpected' };+ const which = LAYERED.find((layer) => layer.label === label);+ reason = `${which ? `${which.label}: ` : ''}${serviceAnswerText(failure)}`;+ }+ return `which forms, views and charts on the spec's tables are saved but not published could not be read (${reason}). Run the build again with --publish, or publish these tables in Power Apps: ${tableList(names, MAX_NAMES)}.`;}if (!read.byTable || !read.byTable.size) return null;const records = (list) => {diff --git a/plugins/model-apps/scripts/lib/temp-workspace.js b/plugins/model-apps/scripts/lib/temp-workspace.jsindex 1a7211593..8b168da8a 100644--- a/plugins/model-apps/scripts/lib/temp-workspace.js+++ b/plugins/model-apps/scripts/lib/temp-workspace.js@@ -352,6 +352,9 @@ function writeWhole(file, text, deps) {const temp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try {fsx.writeFileSync(temp, text, { flag: 'wx', mode: 0o600 });+ // The same short waits as every other refusal in this module (WAITS_MS, through `deps.pause`, and only where there are no owners: windowsRefusesForAMoment), not the longer, process-bounded retry of lib/rename-retry.js: this write is+ // a courtesy that never fails a run, and a sweep or a make must not stall on it. A rename repeated here is safe: the temporary copy is this call's own (`wx`, a name with the pid and a random part) and `file` is+ // whole before and after.// On Windows a scanner that has just seen the new file can hold it for a moment, and the rename is refused (EPERM, EACCES or EBUSY): the same short waits as for the folder.for (let attempt = 0; ; attempt += 1) {try {@@ -478,6 +481,8 @@ function removeWorkspace(dir, deps) {}const file = path.join(dir, OWNER_FILE);const aside = path.join(path.dirname(dir), `${path.basename(dir)}${REMOVING_SUFFIX}`);+ // Not retried (lib/rename-retry.js): this moves the owner record aside as the first step of removing a folder, from a sweep that is bounded in time (see "A SWEEP IS BOUNDED, AND FAIR") — a refusal means this+ // folder is not removed now, which the sweep already treats as "try again on a later sweep", and waiting on each held folder would spend the sweep's whole budget on one.try {fsx.renameSync(file, aside);} catch (e) {@@ -492,6 +497,8 @@ function removeWorkspace(dir, deps) {return true;}try {+ // Not retried: this puts the record back after the folder refused to go, and a failure here is already tolerated (the record stays beside the folder, whole). Repeating it would only delay the error+ // being thrown below, and a record moved back late is no more useful than one beside the folder.fsx.renameSync(aside, file);} catch { /* the record stays beside the folder, whole: see above */ }throw e;diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.jsindex 4bc9c97b2..e12e5d498 100644--- a/plugins/model-apps/scripts/lib/verify-spec.js+++ b/plugins/model-apps/scripts/lib/verify-spec.js@@ -49,6 +49,7 @@ const { verifyDateBehaviors } = require('./date-behavior.js');const { isDeclaredView, compileViewIntent } = require('./view-reconcile.js');const { expectedQuickFindProjection } = require('./quick-find.js');const { readXmlElements, XML_PREDEFINED } = require('./strict-xml.js');+const { usesCommandStates, normalizeCommandStates } = require('./command-state-contract.js');// How many verification reads may be in flight at once. A verify pass is nothing but reads, but each is a// Dataverse request that already retries on its own 429s (lib/sdk-http-client.js), so the bound is small:@@ -1381,6 +1382,35 @@ async function verifySpec(spec, read, opts = {}) {});}+ // Command states: each declared commandStates[] entry's row holds the flags it declares (verifyCommandStates, lib/command-state-read.js). Unlike+ // the existence check above this is not best-effort: a spec that declares states asked for them to be checked, so a reader that cannot read+ // command rows, or a read that fails, fails every entry — never a pass and never left out. Only stored flags are checked, not how the button renders.+ // A verify of a run that did not run the commands phase (exactly --stage data, which leaves command states alone) reports each entry as+ // phase-skipped and reads no row: that run never applied them. A verify with no phase list is unrestricted and still checks every entry.+ const commandsPhaseRan = !ranPhases || ranPhases.has('commands');+ if (usesCommandStates(spec)) {+ plan.each([spec], async ({ add, phaseSkipped }) => {+ const label = (s) => `${s.entity} ${s.bar} row ${s.rowId}`;+ if (!commandsPhaseRan) {+ for (const s of normalizeCommandStates(spec)) phaseSkipped.push(`command-state:${label(s)}`);+ return;+ }+ let checks;+ if (typeof read.commandStates !== 'function') {+ checks = normalizeCommandStates(spec).map((s) => ({ name: label(s), present: false, detail: 'this reader cannot read command rows' }));+ } else {+ try {+ checks = await read.commandStates(spec);+ } catch (error) {+ // Said as the feature says a failed read (lib/command-state-read.js readFailureText): a status and a code, never the service's text.+ const { readFailureText } = require('./command-state-read.js');+ checks = normalizeCommandStates(spec).map((s) => ({ name: label(s), present: false, detail: `could not be read: ${readFailureText(error)}` }));+ }+ }+ for (const c of checks) add('command-state', c.name, c.present, c.detail);+ });+ }+// Web resources: each declared one exists and — unless it is `external`, a shared web resource the build reuses as it finds it and never// writes — holds the content the spec gives it, compared exactly as the build compares it (webResourceContentState, sdk-build.js). A// rebuild never writes the content of a web resource that exists (references/app-spec-schema-advanced.md), so a content edit that was notdiff --git a/plugins/model-apps/scripts/list-command-states.js b/plugins/model-apps/scripts/list-command-states.jsnew file mode 100644index 000000000..7d3da473f--- /dev/null+++ b/plugins/model-apps/scripts/list-command-states.js@@ -0,0 +1,157 @@+#!/usr/bin/env node+'use strict';+// list-command-states: the modern command buttons (`appaction` rows) of an app's tables, each with its row id, its bar, its scope, its stored+// `hidden` / `isdisabled` state, and whether it is a candidate for a row-state edit — and, when it is not, every reason why, in a fixed+// vocabulary (lib/command-state-contract.js, REASONS). Read-only: it sends GET requests and nothing else, and it accepts no write flag.+//+// What it reads (lib/command-state-read.js, through the read-only transport of lib/command-state-transport.js):+// the app by its unique name (every page; exactly one), its current saved layer, its complete list of table components, the named table (or+// every table of the app), whether the table of commands keeps row versions, and every command bound to each table by `contextvalue` — every+// page, every continuation on the same origin.+// A button the listing shows as not a candidate is still a button: a deactivated, managed, migrated, nested, container or another app's row is+// listed with its reasons, never left out, so "no row" is never mistaken for "no button". A bar the App Spec has no name for is `unsupported`,+// never mapped onto MainTab, HomeTab or ContextualTab. Two buttons with the same caption on one bar each carry the other's row id in+// `sameCaption`: pick by row id, never by caption.+// A candidate is a row whose SHAPE allows a row-state edit; the listing proves nothing about how the app renders it.+//+// Usage: node scripts/list-command-states.js --env <envUrl> --app <uniqueName> [--entity <logical>] [--location MainTab|HomeTab|ContextualTab]+// --env the environment's https origin, e.g. https://contoso.crm.dynamics.com+// --app the app's unique name+// --entity one table's logical name (any letter case); without it, every table of the app+// --location only the buttons of one bar+//+// Output (stdout, one pure-ASCII JSON line), exit 0:+// { "ok": true, "app": { "uniqueName": "contoso_Support", "appId": "<guid>" }, "optimisticConcurrency": true,+// "tables": [ { "entity": "contoso_ticket", "metadataId": "<guid>", "inApp": true } ], "count": 2, "candidates": 1,+// "commands": [ { "entity": "contoso_ticket", "location": 0, "bar": "MainTab", "caption": "Escalate", "rowId": "<guid>", "scope": "table",+// "appId": null, "hidden": false, "disabled": false, "type": 0, "origin": 0, "parentId": null, "visibilityType": 0,+// "onClickType": 2, "active": true, "managed": false, "customizable": true, "candidate": true, "reasons": [] }, ... ] }+// `caption` is null for an unlabelled button; `details` (when present) names the columns that could not be read; `sameCaption` lists the+// other buttons with the same caption on the same bar of the same table.+// A failed or incomplete read: { "ok": false, "code": "<command-state-...>", "error": "<message>" } and exit 1 — never an empty success.+//+// Exit codes: 0 read; 1 usage error (stderr names the flag and the usage, stdout stays empty) or a failed read.++const { parseArgs, validateFlags, emitResult, requireDataverseOrigin } = require('./lib/dataverse-auth.js');+const { withThrowawaySdk } = require('./lib/throwaway-sdk.js');+const { makeWritesBlocking } = require('./lib/output-redaction.js');+const { createAzHttpClient } = require('./lib/sdk-http-client.js');+const { createCommandStateTransport } = require('./lib/command-state-transport.js');+const { resolveCommandStateContext, listCommandStateRows } = require('./lib/command-state-read.js');+const { LOCATION_BY_BAR } = require('./lib/command-state-contract.js');+const { TABLE_NAME } = require('./lib/app-components.js');++const USAGE = 'Usage: node scripts/list-command-states.js --env <envUrl> --app <uniqueName> [--entity <logical>] [--location MainTab|HomeTab|ContextualTab]';+const BARS = Object.keys(LOCATION_BY_BAR);+// Flags of the build that change an environment. They are named apart from any other unknown flag so the message says why they are refused.+const WRITE_FLAGS = ['apply', 'publish', 'authorize', 'yes', 'force'];++// One listed button, for the output.+function itemOf({ table, eligible, reasons, details, sameCaption, row }) {+ return {+ entity: table,+ location: row.location,+ bar: row.bar,+ caption: row.caption,+ rowId: row.rowId,+ scope: row.scope,+ appId: row.appId,+ hidden: row.hidden,+ disabled: row.disabled,+ type: row.type,+ origin: row.origin,+ parentId: row.parentId,+ visibilityType: row.visibilityType,+ onClickType: row.onClickType,+ active: row.statecode === 0 && row.statuscode === 1,+ managed: row.managed,+ customizable: row.customizable,+ candidate: eligible,+ reasons,+ ...(details.length ? { details } : {}),+ ...(sameCaption ? { sameCaption } : {}),+ };+}++/**+ * Lists the modern commands of an app's tables.+ * @param {string} env - a Dataverse https origin+ * @param {{ app: string, entity?: string, location?: string }} args+ * @param {object} [httpClient] - the raw az-token client for `env` (a test seam); made here when omitted+ */+async function listCommandStates(env, { app, entity, location } = {}, httpClient) {+ if (location !== undefined && !BARS.includes(location)) throw new Error(`location must be one of ${BARS.join(', ')} (got '${location}')`);+ const client = httpClient || createAzHttpClient(env);+ return withThrowawaySdk({ env, httpClient: client, prefix: 'list-command-states-' }, async (make) => {+ const sdk = make();+ // The SDK says where the API root is; the reads go through the raw client, so each answer is read whole (lib/command-state-transport.js).+ const reader = createCommandStateTransport({ client, apiUrl: (path) => sdk.dataverse.apiUrl(path) });+ const context = await resolveCommandStateContext(reader, { appUniqueName: app, entities: entity ? [entity] : undefined });+ const listed = await listCommandStateRows(reader, context, location === undefined ? {} : { location: LOCATION_BY_BAR[location] });+ const commands = listed.map(itemOf);+ return {+ ok: true,+ app: { uniqueName: context.appUniqueName, appId: context.appId },+ ...(entity ? { entity } : {}),+ ...(location !== undefined ? { location } : {}),+ optimisticConcurrency: context.optimisticConcurrency,+ tables: [...context.tables.values()].map((table) => ({ entity: table.entity, metadataId: table.metadataId, inApp: table.inApp })),+ count: commands.length,+ candidates: commands.filter((item) => item.candidate).length,+ commands,+ };+ });+}++function usageError(message) {+ makeWritesBlocking(process.stdout, process.stderr);+ process.stderr.write(`✗ ${message}\n${USAGE}\n`);+ process.exit(1);+}++async function main() {+ const argv = process.argv.slice(2);+ const { positional, flags } = parseArgs(argv);+ const writeFlag = argv.find((arg) => typeof arg === 'string' && WRITE_FLAGS.includes(arg.replace(/^--/, '').split('=')[0]) && arg.startsWith('--'));+ if (writeFlag) usageError(`${writeFlag.split('=')[0]} is not accepted: list-command-states only reads`);+ const flagError = validateFlags(argv, { known: ['env', 'app', 'entity', 'location'], needValue: ['env', 'app', 'entity', 'location'], hints: { location: BARS.join(', ') } });+ if (flagError) usageError(flagError);+ if (positional.length) usageError(`unexpected argument '${positional[0]}'`);+ if (!flags.env) usageError('--env is required');+ if (!flags.app) usageError('--app is required: the app\'s unique name');+ let env;+ try {+ env = requireDataverseOrigin(flags.env);+ } catch (err) {+ usageError(err.message);+ }+ const entity = flags.entity === undefined ? undefined : String(flags.entity).trim().toLowerCase();+ if (entity !== undefined && !TABLE_NAME.test(entity)) usageError(`--entity '${flags.entity}' is not a table's logical name`);+ const location = flags.location === undefined ? undefined : String(flags.location);+ if (location !== undefined && !BARS.includes(location)) usageError(`--location must be one of ${BARS.join(', ')} (got '${flags.location}')`);++ // emitResult() ends the process, so the read's outcome is settled first and emitted outside the try.+ let result;+ let failure;+ try {+ result = await listCommandStates(env, { app: String(flags.app), entity, location });+ } catch (err) {+ failure = err;+ }+ if (failure) {+ const code = failure && typeof failure.code === 'string' ? failure.code : undefined;+ emitResult(false, { ok: false, ...(code ? { code } : {}), error: String((failure && failure.message) || failure) }, { ascii: true });+ return;+ }+ emitResult(true, result, { ascii: true });+}++module.exports = { listCommandStates };++if (require.main === module) {+ main().catch((err) => {+ makeWritesBlocking(process.stdout, process.stderr);+ process.stderr.write(`Error: ${err.message}\n`);+ process.exit(1);+ });+}diff --git a/plugins/model-apps/scripts/tests/apply-snapshot-store.test.js b/plugins/model-apps/scripts/tests/apply-snapshot-store.test.jsindex 456cf5050..d792ca3cd 100644--- a/plugins/model-apps/scripts/tests/apply-snapshot-store.test.js+++ b/plugins/model-apps/scripts/tests/apply-snapshot-store.test.js@@ -6,6 +6,8 @@ const os = require('node:os');const path = require('node:path');const store = require('../lib/apply-snapshot-store.js');const S = require('../lib/apply-snapshot.js');+const { shortRenameWait } = require('./helpers/short-rename-wait.js');+// Each test gets its own throwaway workspace so the real filesystem I/O can't cross-contaminate.function ws() {@@ -37,6 +39,7 @@ test('writeSnapshotAtomic + readSnapshot round-trip and leave NO temp file behin// step — the write, the fsync, the rename — leaves the target exactly as it was and no temp beside it, and the text// lands whole however the OS splits the write (a short write fsynced and renamed into place is a partial file).test('writeFileAtomic leaves the target as it was, and no temp, when any step fails — and writes the whole text', (t) => {+ shortRenameWait(t);const d = ws();try {const target = path.join(d, 'file.json');@@ -67,6 +70,7 @@ test('writeFileAtomic leaves the target as it was, and no temp, when any step fa});test('writeSnapshotAtomic writes through writeFileAtomic: a write that fails leaves the previous snapshot', (t) => {+ shortRenameWait(t);const d = ws();try {store.writeSnapshotAtomic(d, eligible('g1'));diff --git a/plugins/model-apps/scripts/tests/build-model-app.test.js b/plugins/model-apps/scripts/tests/build-model-app.test.jsindex cf24a5c06..cf1942853 100644--- a/plugins/model-apps/scripts/tests/build-model-app.test.js+++ b/plugins/model-apps/scripts/tests/build-model-app.test.js@@ -2766,34 +2766,27 @@ test('build --verify wires readers that verify-spec will NOT skip role-privilege// the build can hand verify the artifacts this ENVIRONMENT could not host (an environment-gated// business-rule skip must not read as "not deployed"). Pinning `(s)` exactly made this test fail// for a change that did not touch what it is actually guarding. The lambda now makes (and disposes)- // the page backend around that call, so the line is found by what it calls.- const call = src.split(/\r?\n/).find((l) => /verifySpec\(\s*s\s*,\s*readerFor\(provisionSdk,/.test(l));+ // the page backend around that call, so the line is found by what it calls. The reader itself is made by+ // inlineVerifyReader from the whole makeSdk result (`made`), so a reader makeSdk hands back cannot be left+ // out at this line.+ const call = src.split(/\r?\n/).find((l) => /verifySpec\(\s*s\s*,\s*inlineVerifyReader\(made,/.test(l));assert.ok(call, 'expected the deps.verify wiring line');- assert.match(call, /readerFor\(provisionSdk,/, 'verify must read through the provisioning SDK');// The second argument must actually be forwarded, or the environment-skip list is silently// dropped and verify keeps failing on rules the build already reported it could not create.assert.match(call, /verifySpec\(\s*s\s*,[\s\S]*\)\s*,\s*verifyOpts\s*\)/,'the caller-supplied verify options must reach verifySpec');-- // The substantive half: the option bag on that line, fed to the real `readerFor`, must yield BOTH- // privilege readers. A source match alone would keep passing if `entityPrivileges` were made- // conditional again on something the build does not supply.- const optsSrc = /readerFor\(provisionSdk,[^,]+,\s*(\{[^}]*\})\s*\)/.exec(call);- assert.ok(optsSrc, `could not extract the readerFor options from: ${call}`);- // Shorthand-aware: `{ genpage, workspaceDir, isolatedReader }` carries only SHORTHAND keys, and a- // colon-only pattern would see none of them, which would make the assertion below weaker than it- // looks — it would have kept passing for an option bag that had lost `workspaceDir` entirely.- // Match a name followed by `:`, `,` or `}`.- const optKeys = [...optsSrc[1].matchAll(/([A-Za-z_$][\w$]*)\s*(?::|[,}])/g)].map((m) => m[1]);- assert.ok(optKeys.includes('workspaceDir') && optKeys.includes('genpage'),- `expected both readerFor options to be extracted, got ${JSON.stringify(optKeys)}`);- const { readerFor } = require('../verify-model-app.js');- // A bare object is enough: every base reader is a lazy closure, so this asserts PRESENCE, which is- // exactly what verify-spec's method-presence gate tests.- const reader = readerFor({}, 'contoso_app', Object.fromEntries(optKeys.map((k) => [k, k === 'workspaceDir' ? __dirname : {}])));+ const helper = src.slice(src.indexOf('function inlineVerifyReader'), src.indexOf('\n}\n', src.indexOf('function inlineVerifyReader')));+ assert.match(helper, /readerFor\(made\.provisionSdk,/, 'verify must read through the provisioning SDK');++ // The substantive half: the real helper, fed what makeSdk returns, must yield BOTH privilege readers. A+ // source match alone would keep passing if `entityPrivileges` were made conditional again on something+ // the build does not supply. A bare object is enough: every base reader is a lazy closure, so this asserts+ // PRESENCE, which is exactly what verify-spec's method-presence gate tests.+ const { inlineVerifyReader } = require('../build-model-app.js');+ const reader = inlineVerifyReader({ provisionSdk: {}, isolatedReader: {} }, { app: { uniqueName: 'contoso_app' } }, { genpage: {}, workspaceDir: __dirname });for (const name of ['rolePrivileges', 'entityPrivileges']) {assert.strictEqual(typeof reader[name], 'function',- `verify-spec silently skips role-privileges without '${name}'; the build's options are ${JSON.stringify(optKeys)}`);+ `verify-spec silently skips role-privileges without '${name}'`);}});@@ -2807,11 +2800,16 @@ test('makeSdk\u2019s return shape and main\u2019s destructure stay in agreement'const returned = /return \{ ([^}]*) \};/.exec(src.slice(src.indexOf('function makeSdk')));assert.ok(returned, 'expected makeSdk to return an object literal');// `await` is optional in the pattern: `makeSdk` became async when the SDK's workspace calls did,- // and this guard is about the KEY SETS agreeing, not about how the promise is unwrapped.- const destructured = /const \{ ([^}]*) \} = (?:await\s+)?makeSdk\(/.exec(src);- assert.ok(destructured, 'expected main to destructure makeSdk()');+ // and this guard is about the KEY SETS agreeing, not about how the promise is unwrapped. main keeps+ // the whole result as `made` (the inline verify reader takes all of it) and destructures the rest, so+ // the keys it uses are the destructured ones plus those inlineVerifyReader reads off `made`.+ assert.match(src, /const made = await makeSdk\(/, 'expected main to keep makeSdk()\u2019s result');+ const destructured = /const \{ ([^}]*) \} = made;/.exec(src);+ assert.ok(destructured, 'expected main to destructure makeSdk()\u2019s result');+ const helper = src.slice(src.indexOf('function inlineVerifyReader'), src.indexOf('\n}\n', src.indexOf('function inlineVerifyReader')));const names = (s) => s.split(',').map((x) => x.trim()).filter(Boolean).sort();- assert.deepStrictEqual(names(destructured[1]), names(returned[1]),+ const used = [...new Set([...names(destructured[1]), ...[...helper.matchAll(/made\.([A-Za-z_$][\w$]*)/g)].map((m) => m[1])])].sort();+ assert.deepStrictEqual(used, names(returned[1]),'main destructures keys makeSdk does not return (or ignores ones it does)');});@@ -2825,7 +2823,9 @@ test('the build verifies dashboards through makeSdk\u2019s isolated reader, sharassert.match(body, /const httpClient = createAzHttpClient\(env, \{ throttle, sendOnce: \(method, url\) => isTranslationExport\(method, url\) \|\| configurationSendOnce\(method, url\), \.\.\.\(publicationBarrier \? \{ request: publicationBarrier\.gateRequest\(sendObserver \? sendObserver\.wrap\(\) : undefined\) \} : \{\}\), \.\.\.\(writeGate \? \{ workflowEffectGate: writeGate \} : \{\}\) \}\);/, 'one client, made with the run\u2019s throttle budget, that sends a translation export, and a configuration write, once and checks every publish at the publication barrier\u2019s send gate, with the managed attempts\u2019 send observer inside the gate, and screens a declared workflow write (and a protected configuration create) with the build\u2019s write gate only when it has one');assert.match(body, /isolatedReaderFor\(env, \{ httpClient \}\)/, 'the reader is made around the build\u2019s own client');const wiring = src.slice(src.indexOf('verify: async (s, verifyOpts) =>'));- assert.match(wiring.split(/\r?\n/).find((l) => /verifySpec\(/.test(l)), /isolatedReader \}/, 'verify takes the reader makeSdk returned');+ assert.match(wiring.split(/\r?\n/).find((l) => /verifySpec\(/.test(l)), /inlineVerifyReader\(made, /, 'verify takes the readers makeSdk returned');+ const helper = src.slice(src.indexOf('function inlineVerifyReader'), src.indexOf('\n}\n', src.indexOf('function inlineVerifyReader')));+ assert.match(helper, /isolatedReader: made\.isolatedReader/, 'including the isolated reader');assert.strictEqual((src.match(/isolatedReaderFor\(/g) || []).length, 1, 'no second reader, and so no second client, is made');});diff --git a/plugins/model-apps/scripts/tests/changed-only-flow.test.js b/plugins/model-apps/scripts/tests/changed-only-flow.test.jsindex 387971b04..28b827df0 100644--- a/plugins/model-apps/scripts/tests/changed-only-flow.test.js+++ b/plugins/model-apps/scripts/tests/changed-only-flow.test.js@@ -356,6 +356,24 @@ test('run: with protected configuration in play (a managed-create gate) neither}});+// commandStates are applied only by a full build, which reads every declared row and asks for approval of what it finds: an unchanged spec is not+// proof that a row still holds its flags (it can have been edited in the designer since), so neither a NOOP nor a FAST apply is taken.+test('run: a spec that declares commandStates never takes a NOOP or a FAST apply — the full build runs', async () => {+ const withStates = () => ({ ...baseSpec(), commandStates: [{ entity: 'new_x', location: 'MainTab', scope: 'table', rowId: '11111111-1111-4111-8111-111111111111', hidden: true }] });+ for (const content of ['v1', 'v2']) {+ const dir = ws();+ try {+ seedEligible(dir, annotate(withStates(), 'v1'));+ const record = [];+ const r = await flow.runChangedOnlyApply({ spec: withStates(), opts: { workspaceDir: dir, apply: true }, deps: baseDeps(dir, { buildModelApp: stubBuild(record), readContent: readFor(content) }) });+ assert.notStrictEqual(r.noop, true, content);+ assert.strictEqual(r.changedOnly.decision, 'full', content);+ assert.strictEqual(r.changedOnly.reason, flow.COMMAND_STATES_FULL, content);+ assert.strictEqual(record.length, 1, `${content}: the full build ran`);+ assert.strictEqual(record[0].phases, undefined, `${content}: every phase`);+ } finally { rm(dir); }+ }+});test('run: FULL baseline (fresh app, appId null at start) writes an ELIGIBLE snapshot', async () => {const dir = ws();try {diff --git a/plugins/model-apps/scripts/tests/command-state-build.test.js b/plugins/model-apps/scripts/tests/command-state-build.test.jsnew file mode 100644index 000000000..a79cdea30--- /dev/null+++ b/plugins/model-apps/scripts/tests/command-state-build.test.js@@ -0,0 +1,628 @@+'use strict';+// commandStates[] through the build's own entry point (lib/sdk-build.js runSdkBuild): the plan a dry run prints, the refusals that come before the+// build writes anything, the one conditional flag-only PATCH an approved apply sends, the outcomes of that PATCH, and the table publication the+// apply must see before it reports success. The SDK is the light mock (helpers/mock-sdk.js) with a raw client for the before-app table publish;+// the command rows are the fake org of helpers/command-state-org.js, reached through the real raw client (createAzHttpClient) and the feature's+// own transport, so the retry and send-once behaviour under test is the shipped one.++const test = require('node:test');+const assert = require('node:assert');+const { inOwnFolder } = require('./helpers/own-app-folder.js');+const runSdkBuild = inOwnFolder(require('../lib/sdk-build.js').runSdkBuild);+const { commandRow, json, ORIGIN, APP_ID } = require('./helpers/command-state-org.js');+const { T, MD, ROW, HIDE, APPLY, specFor, harness, buildWithJournal } = require('./helpers/command-state-build-harness.js');++const ROW2 = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';+// A legacy commands[] button and the script it runs.+const LEGACY = (extra = {}) => ({ commands: [{ entity: T, label: 'Go', library: 'new_go.js', function: 'Ns.go', ...extra }], webResources: [{ name: 'new_go.js', type: 'js', content: 'var Ns = {};' }] });++test('a dry run reads each declared row and prints the exact approvals; it writes and publishes nothing', async () => {+ const h = harness();+ const { plan } = await h.approve(specFor());+ assert.strictEqual(plan.status, 'planned');+ assert.strictEqual(plan.rows.length, 1);+ assert.deepStrictEqual(plan.rows[0].change, { hidden: true });+ assert.match(plan.rows[0].approval, new RegExp(`^overwrite:command-state:${T}/MainTab/${ROW}/[0-9a-f]{64}$`));+ assert.match(plan.rows[0].description, /table scope: every app that shows this table/);+ assert.deepStrictEqual(plan.tables.map((t) => t.entity), [T]);+ assert.match(plan.tables[0].token, new RegExp(`^publish:command-state-table:${T}/[0-9a-f]{64}$`));+ assert.deepStrictEqual(h.org.writes(), []);+ assert.deepStrictEqual(h.published, []);+ assert.deepStrictEqual(h.org.unexpected, []);+});++test('an approved apply sends one conditional, flag-only PATCH, publishes the table before the app and reports both', async () => {+ const h = harness();+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ const { res, error } = await h.build(spec, { ...APPLY, commandStateApprovals: approvals });+ assert.ifError(error);+ assert.strictEqual(res.ok, true);+ const sent = h.patches();+ assert.strictEqual(sent.length, 1, 'one exact flag-only conditional PATCH was captured');+ assert.strictEqual(sent[0].path, `/appactions(${ROW})`);+ assert.strictEqual(sent[0].headers['If-Match'], 'W/"1001"');+ assert.deepStrictEqual(sent[0].body, { hidden: true });+ assert.ok(!Object.keys(sent[0].headers).some((k) => /solutionuniquename/i.test(k)), 'a reused row is never put into a solution');+ assert.ok(h.published.some((names) => names.includes(T)), `the table is named in a before-app publish: ${JSON.stringify(h.published)}`);+ assert.deepStrictEqual(res.commandStates.rows.map((r) => [r.rowId, r.outcome, r.changed]), [[ROW, 'acknowledged', ['hidden']]]);+ assert.deepStrictEqual(res.commandStates.publication.map((p) => [p.entity, p.outcome]), [[T, 'confirmed']]);+ assert.deepStrictEqual(h.org.unexpected, []);+});++test('false is an instruction and is sent; a flag the entry leaves out is never sent; visibilitytype is never written', async () => {+ const h = harness({ rows: [commandRow(ROW, T, MD, { hidden: true, isdisabled: true })] });+ const spec = specFor([{ entity: T, location: 'MainTab', scope: 'table', rowId: ROW, hidden: false }]);+ const { approvals } = await h.approve(spec);+ const { error } = await h.build(spec, { ...APPLY, commandStateApprovals: approvals });+ assert.ifError(error);+ assert.deepStrictEqual(h.patches().map((r) => r.body), [{ hidden: false }]);+});++test('a row that already holds the declared flags is not written, and its table is still published and confirmed', async () => {+ const h = harness({ rows: [commandRow(ROW, T, MD, { hidden: true })] });+ const spec = specFor();+ const { plan, approvals } = await h.approve(spec);+ assert.deepStrictEqual(plan.rows[0].change, {});+ const { res, error } = await h.build(spec, { ...APPLY, commandStateApprovals: approvals });+ assert.ifError(error);+ assert.deepStrictEqual(h.patches(), []);+ assert.ok(h.published.some((names) => names.includes(T)));+ assert.deepStrictEqual(res.commandStates.publication.map((p) => p.outcome), ['confirmed']);+});++test('an apply without every approval stops before the build writes anything at all', async () => {+ for (const which of ['none', 'rows only', 'tables only']) {+ const h = harness();+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ const given = which === 'none' ? {} : which === 'rows only' ? { rows: approvals.rows } : { tables: approvals.tables };+ const { error, calls } = await h.build(spec, { ...APPLY, commandStateApprovals: given });+ assert.ok(error, which);+ assert.match(error.code, /^command-state-(publication-)?approval-required$/, which);+ assert.deepStrictEqual(h.org.writes(), [], `${which}: no row write`);+ assert.deepStrictEqual(h.published, [], `${which}: no publish`);+ assert.deepStrictEqual(calls.filter(([name]) => /^(create|update|add|push|publish|set|seed|enrich|configure|delete)/.test(name)), [], `${which}: no build write (solution, table, app)`);+ }+});++test('a row that changed after it was approved is not written: the approval is stale', async () => {+ const rows = [commandRow(ROW, T, MD)];+ const h = harness({ rows });+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ rows[0]['@odata.etag'] = 'W/"1002"';+ const { error } = await h.build(spec, { ...APPLY, commandStateApprovals: approvals });+ assert.strictEqual(error && error.code, 'command-state-approval-stale');+ assert.deepStrictEqual(h.org.writes(), []);+});++test('a row changed between the read and the write is refused 412, never sent again and never overwritten', async () => {+ const rows = [commandRow(ROW, T, MD)];+ const h = harness({+ rows,+ overrides: (req) => { if (req.method === 'PATCH') { rows[0]['@odata.etag'] = 'W/"2000"'; rows[0].buttonlabeltext = 'Someone else'; } return undefined; },+ });+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ const { error } = await h.build(spec, { ...APPLY, commandStateApprovals: approvals });+ assert.strictEqual(error && error.code, 'command-state-version-conflict');+ assert.strictEqual(h.patches().length, 1);+ assert.strictEqual(rows[0].hidden, false, 'the newer row is kept');+ assert.deepStrictEqual(error.commandStates.rows.map((r) => [r.outcome, r.code]), [['refused', 'command-state-version-conflict']]);+});++test('a write whose answer is lost or throttled is sent exactly once and reported as unknown', async () => {+ for (const [what, answer] of [+ ['503', () => json(503, { error: { code: '0x80072321', message: 'unavailable' } })],+ ['429', () => json(429, { error: { code: '0x80072322', message: 'throttled' } }, { 'retry-after': '1' })],+ ['cut', () => { throw Object.assign(new Error('socket hang up: planted-service-message W/"498763"'), { code: 'ECONNRESET' }); }],+ ]) {+ const h = harness({ overrides: (req) => (req.method === 'PATCH' ? answer() : undefined) });+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ const { error } = await h.build(spec, { ...APPLY, commandStateApprovals: approvals });+ assert.strictEqual(h.patches().length, 1, `${what}: sent once`);+ assert.strictEqual(error && error.code, 'command-state-write-unknown', what);+ assert.strictEqual(error.retry && error.retry.kind !== undefined ? error.retry.kind : error.retry, require('../lib/retry-policy.js').RETRY.NEVER, `${what}: never retried`);+ // A write with no answer says why by its system code alone, never by the error's own text.+ if (what === 'cut') {+ assert.match(error.message, /\[no usable answer \(ECONNRESET\); check the connection and run it again\]/, error.message);+ assert.ok(!error.message.includes('planted-service-message') && !error.message.includes('498763'), error.message);+ }+ }+});++test('a write that landed although its answer was lost is reported from the row read back, and still not sent again', async () => {+ const h = harness({ afterPatch: () => json(503, { error: { code: '0x80072321', message: 'unavailable' } }) });+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ const { res, error } = await h.build(spec, { ...APPLY, commandStateApprovals: approvals });+ assert.strictEqual(h.patches().length, 1);+ const rows = (res || error).commandStates.rows;+ assert.deepStrictEqual(rows.map((r) => r.outcome), ['observed-matching-after-unknown-send']);+});++test('a table publish that is refused leaves the write saved but unconfirmed, and the apply fails saying so', async () => {+ const h = harness({ publishStatus: 500 });+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ const { error } = await h.build(spec, { ...APPLY, commandStateApprovals: approvals });+ assert.ok(error, 'the apply does not report success');+ assert.strictEqual(error.code, 'command-state-publish-unconfirmed');+ assert.strictEqual(h.patches().length, 1);+ assert.deepStrictEqual(error.commandStates.publication.map((p) => [p.entity, p.outcome]), [[T, 'unconfirmed']]);+ assert.deepStrictEqual(error.commandStatePublicationError.tables, [T]);+});++test('an app-scoped row is refused before any write, even one scoped to this app', async () => {+ const h = harness({ rows: [commandRow(ROW, T, MD, { _appmoduleid_value: APP_ID })] });+ const spec = specFor();+ const { error } = await h.build(spec, { ...APPLY, commandStateApprovals: { rows: new Set(), tables: new Set() } });+ assert.strictEqual(error && error.code, 'command-state-app-scope-unverified');+ assert.deepStrictEqual(h.org.writes(), []);+});++test('commands[] that would create a new bar on a table whose row commandStates edits is refused before the create', async () => {+ const h = harness();+ const spec = specFor([HIDE], LEGACY());+ const { approvals } = await h.approve(spec);+ const { error, calls } = await h.build(spec, { ...APPLY, commandStateApprovals: approvals });+ assert.strictEqual(error && error.code, 'command-state-legacy-create-conflict');+ assert.deepStrictEqual(calls.filter(([name, kind]) => name === 'createArtifact' && kind === 'command'), []);+ assert.deepStrictEqual(h.org.writes(), []);+});++test('only a full build with --publish applies command states: anything else is refused before it writes, and exactly --stage data leaves them alone', async () => {+ const { STAGES } = require('../lib/stages.js');+ for (const [what, opts, code] of [+ ['no --publish', { apply: true, publish: false }, 'command-state-publish-required'],+ ['a partial apply', { apply: true, publish: true, phases: ['commands'] }, 'command-state-phase-unsupported'],+ ]) {+ const h = harness();+ const { error, calls } = await h.build(specFor(), opts);+ assert.strictEqual(error && error.code, code, what);+ assert.deepStrictEqual(h.org.requests, [], `${what}: nothing read or written`);+ assert.deepStrictEqual(calls.filter(([name]) => /^(create|update|add|push|publish|set|seed)/.test(name)), [], what);+ }+ const keyed = harness();+ const { error } = await keyed.build(specFor([HIDE], LEGACY({ key: 'go' })), APPLY);+ assert.strictEqual(error && error.code, 'command-state-keyed-unsupported');+ {+ const h = harness();+ const { error: dataError, warnings } = await h.build(specFor(), { apply: true, publish: true, phases: STAGES.data });+ assert.ifError(dataError);+ assert.deepStrictEqual(h.org.requests, [], '--stage data reads no command row');+ assert.ok(warnings.some((w) => /commandStates/.test(w)), 'and says the states were not applied');+ }+});++test('a spec without commandStates builds as before: no command row is read and no result is added', async () => {+ const h = harness();+ const { res, error } = await h.build(specFor(null), APPLY);+ assert.ifError(error);+ assert.strictEqual(res.ok, true);+ assert.deepStrictEqual(h.org.requests, []);+ assert.strictEqual(res.commandStates, undefined);+ const dry = await h.build(specFor(null), { apply: false });+ assert.strictEqual(dry.res.commandStatePlan, undefined);+ const empty = harness();+ const out = await empty.build(specFor([]), APPLY);+ assert.ifError(out.error);+ assert.strictEqual(out.res.ok, true, 'an empty list is the feature switched off, as absent is');+ assert.deepStrictEqual(empty.org.requests, []);+ assert.strictEqual(out.res.commandStates, undefined);+});++test('the engine checks commandStates itself: a direct caller with an app-scoped or malformed declaration is stopped before any request', async () => {+ for (const [what, commandStates, code] of [+ ['app scope', [{ ...HIDE, scope: 'app' }], 'command-state-app-scope-unverified'],+ ['null', null, 'command-state-spec-invalid'],+ ['an object, not a list', { ...HIDE }, 'command-state-spec-invalid'],+ ['a commands[] field', [{ ...HIDE, label: 'Go' }], 'command-state-spec-invalid'],+ ['app scope and a malformed flag', [{ ...HIDE, scope: 'app', hidden: 'yes' }], 'command-state-spec-invalid'],+ ]) {+ for (const mode of ['apply', 'dry run']) {+ const h = harness();+ // Exact approvals for the valid declaration: the bad one must not ride on them.+ const { approvals } = await h.approve(specFor());+ const mark = h.org.requests.length;+ const { error, calls } = await h.build({ ...specFor(), commandStates }, mode === 'apply' ? { ...APPLY, commandStateApprovals: approvals } : { apply: false });+ assert.strictEqual(error && error.code, code, `${what} (${mode})`);+ assert.match(error.message, /commandStates/, `${what} (${mode}): the halt names the field`);+ assert.deepStrictEqual(h.org.requests.slice(mark), [], `${what} (${mode}): no command row is read or written`);+ assert.deepStrictEqual(calls, [], `${what} (${mode}): the SDK is not called`);+ assert.deepStrictEqual(h.published, [], `${what} (${mode}): nothing is published`);+ }+ }+});++test('two rows on one table: each is written once, and one publish of the table confirms both', async () => {+ const h = harness({ rows: [commandRow(ROW, T, MD), commandRow(ROW2, T, MD, { location: 1 })] });+ const spec = specFor([HIDE, { entity: T, location: 'HomeTab', scope: 'table', rowId: ROW2, disabled: true }]);+ const { plan, approvals } = await h.approve(spec);+ assert.strictEqual(plan.rows.length, 2);+ assert.strictEqual(plan.tables.length, 1, 'one table approval covers both rows');+ const { res, error } = await h.build(spec, { ...APPLY, commandStateApprovals: approvals });+ assert.ifError(error);+ assert.deepStrictEqual(h.patches().map((r) => [r.path, r.body]), [[`/appactions(${ROW})`, { hidden: true }], [`/appactions(${ROW2})`, { isdisabled: true }]]);+ assert.deepStrictEqual(res.commandStates.publication.map((p) => p.outcome), ['confirmed']);+});++test('every row is read again before the first write: one changed after the preflight stops the apply with no row written', async () => {+ const rows = [commandRow(ROW, T, MD), commandRow(ROW2, T, MD, { location: 1 })];+ let armed = false;+ let reads = 0;+ // The apply reads ROW2 at its preflight, then again in the commands phase; it changes in between.+ const overrides = (req) => {+ if (armed && req.method === 'GET' && req.path.startsWith(`/appactions(${ROW2})`) && ++reads === 2) rows[1]['@odata.etag'] = 'W/"3000"';+ return undefined;+ };+ const h = harness({ rows, overrides });+ const spec = specFor([HIDE, { entity: T, location: 'HomeTab', scope: 'table', rowId: ROW2, disabled: true }]);+ const { approvals } = await h.approve(spec);+ armed = true;+ const { error } = await h.build(spec, { ...APPLY, commandStateApprovals: approvals });+ assert.strictEqual(error && error.code, 'command-state-approval-stale');+ assert.ok(reads >= 2, `the row was read at the preflight and again before any write (${reads})`);+ assert.deepStrictEqual(h.patches(), [], 'no row was written, not even the one that did not change');+});++test('the final proof resolves the app afresh after the build\'s app work: a table no longer in the app fails the apply, and the written row stays reported as written', async () => {+ const tables = { [T]: { metadataId: MD } };+ // The before-app publication is the last shared step before the final proof; the table leaves the app there, after the commands phase.+ const h = harness({ tables, onPublish: () => { tables[T].inApp = false; } });+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ const { error } = await h.build(spec, { ...APPLY, commandStateApprovals: approvals });+ assert.strictEqual(error && error.code, 'command-state-context-unverified', error && error.message);+ assert.match(error.message, /checked again at the end of the build, after its app work; nothing is rolled back \(command state [^)]*: written by this build: the write was accepted and read back holding the declared flags; then the row could not be read and judged at the end of the build \(command-state-context-unverified\)\)/);+ assert.strictEqual(h.patches().length, 1, 'the row was written once and is never written again or undone');+ assert.deepStrictEqual(error.commandStates.rows.map((r) => [r.rowId, r.outcome]), [[ROW, 'acknowledged']], 'the row outcome is what was observed');+ assert.deepStrictEqual(error.commandStates.publication.map((p) => [p.entity, p.outcome]), [[T, 'confirmed']], 'and the publication that ran stands');+ assert.strictEqual(error.commandStatePublicationError, undefined);+});++test('the final proof also fails a row that no longer holds the declared flags after the publication', async () => {+ const rows = [commandRow(ROW, T, MD)];+ const h = harness({ rows, onPublish: () => { rows[0].hidden = false; } });+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ const { error } = await h.build(spec, { ...APPLY, commandStateApprovals: approvals });+ assert.strictEqual(error && error.code, 'command-state-not-confirmed', error && error.message);+ assert.match(error.message, /nothing is rolled back \(.*\): .*then a read at the end of the build found hidden false, disabled false, not the declared flags/);+ assert.match(error.message, /: command state [^:]+: written by this build: the write was accepted and read back holding the declared flags; then a read at the end of the build found hidden false, disabled false, not the declared flags — this build did not overwrite that change/);+ assert.match(error.message, /this build did not overwrite that change/);+ assert.strictEqual(h.patches().length, 1);+ assert.strictEqual(error.commandStates.rows[0].outcome, 'acknowledged');+});++test('the final proof reads every declared row: two rows changed after the publication are both read, noted and named, with the first one\'s code', async () => {+ const finalReads = (error) => error.commandStates.rows.map((r) => [r.rowId, r.facts.filter((f) => f.phase === 'final').map((f) => f.result)]);+ for (const [what, change, overrides, reads, code] of [+ ['both changed', (rows) => { rows[0].hidden = false; rows[1].isdisabled = false; }, () => undefined, ['differed', 'differed'], 'command-state-not-confirmed'],+ // The first row changed and the second could not be read: the code is still the first failure's.+ ['one changed, one unreadable', (rows) => { rows[0].hidden = false; }, (req) => (req.method === 'GET' && req.path.startsWith(`/appactions(${ROW2})`) ? json(503, {}) : undefined), ['differed', 'unreadable'], 'command-state-not-confirmed'],+ // The first row could not be read and the second changed: the code is the unreadable row's, as it was when the proof stopped there.+ ['one unreadable, one changed', (rows) => { rows[1].isdisabled = false; }, (req) => (req.method === 'GET' && req.path.startsWith(`/appactions(${ROW})`) ? json(503, {}) : undefined), ['unreadable', 'differed'], 'command-state-row-unreadable'],+ ]) {+ const rows = [commandRow(ROW, T, MD), commandRow(ROW2, T, MD, { location: 1 })];+ let armed = false;+ const h = harness({ rows, overrides: (req) => (armed ? overrides(req) : undefined), onPublish: () => { armed = true; change(rows); } });+ const spec = specFor([HIDE, { entity: T, location: 'HomeTab', scope: 'table', rowId: ROW2, disabled: true }]);+ const { approvals } = await h.approve(spec);+ const { error } = await h.build(spec, { ...APPLY, commandStateApprovals: approvals });+ assert.strictEqual(error && error.code, code, `${what}: ${error && error.message}`);+ assert.strictEqual(error.retry, require('../lib/retry-policy.js').RETRY.NEVER, what);+ assert.deepStrictEqual(finalReads(error), [[ROW, [reads[0]]], [ROW2, [reads[1]]]], `${what}: every row was read once at the end`);+ assert.strictEqual(h.patches().length, 2, `${what}: nothing more was written`);+ assert.deepStrictEqual(error.commandStates.rows.map((r) => r.outcome), ['acknowledged', 'acknowledged'], what);+ // The halt names both rows after the preface, the first failure first.+ const after = error.message.slice(error.message.indexOf('): ') + 3);+ assert.ok(after.indexOf(ROW) >= 0 && after.indexOf(ROW2) > after.indexOf(ROW), `${what}: ${after}`);+ if (reads[0] === 'differed') assert.match(after, /^command state [^:]+: written by this build: [^;]*; then a read at the end of the build found hidden false, disabled false, not the declared flags — this build did not overwrite that change/, what);+ }+});++test('a row this build left unchanged that drifts before the final proof fails without a write being claimed', async () => {+ const rows = [commandRow(ROW, T, MD, { hidden: true })];+ const h = harness({ rows, onPublish: () => { rows[0].hidden = false; rows[0]['@odata.etag'] = 'W/"2000"'; } });+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ const { error } = await h.build(spec, { ...APPLY, commandStateApprovals: approvals });+ assert.strictEqual(error && error.code, 'command-state-not-confirmed', error && error.message);+ assert.strictEqual(h.patches().length, 0, 'the row held the flags through the commands phase');+ assert.strictEqual(error.commandStates.rows[0].outcome, 'unchanged');+ assert.deepStrictEqual(error.commandStates.rows[0].changed, []);+ assert.strictEqual(error.commandStates.publication[0].outcome, 'confirmed');+ assert.match(error.message, /: command state [^:]+: not written by this build \(it already held the declared flags\); then a read at the end of the build found hidden false, disabled false, not the declared flags — /);+ assert.doesNotMatch(error.message, /accept|acknowledg|sav(e|ed|ing)\b|this build's write/i, 'no write of this build is claimed');+});++test('an unanswered write whose row a competing edit made match, then changed again, fails the final proof without claiming the write', async () => {+ const rows = [commandRow(ROW, T, MD)];+ // The PATCH is answered 503 and never stored; someone else sets the same flag (a new version) before the read that follows it.+ const overrides = (req) => {+ if (req.method !== 'PATCH') return undefined;+ rows[0].hidden = true;+ rows[0]['@odata.etag'] = 'W/"1500"';+ return json(503, { error: { code: '0x80072321', message: 'unavailable' } });+ };+ const h = harness({ rows, overrides, onPublish: () => { rows[0].hidden = false; rows[0]['@odata.etag'] = 'W/"1600"'; } });+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ const { error } = await h.build(spec, { ...APPLY, commandStateApprovals: approvals });+ assert.strictEqual(error && error.code, 'command-state-not-confirmed', error && error.message);+ assert.strictEqual(h.patches().length, 1, 'sent once, never again');+ assert.strictEqual(error.commandStates.rows[0].outcome, 'observed-matching-after-unknown-send', 'the outcome recorded at the write stays');+ assert.strictEqual(error.commandStates.publication[0].outcome, 'confirmed');+ assert.strictEqual(error.commandStatePublicationError, undefined);+ assert.match(error.message, /this build's write got no usable answer \(HTTP 503\), so its outcome is unknown; a later read found the declared flags, which is not proof this build saved them; then a read at the end of the build found hidden false/);+ assert.doesNotMatch(error.message.replaceAll('not proof this build saved them', ''), /accept|acknowledg|sav(e|ed|ing)\b|(?<!not )written by this build/i, 'the unanswered write is not claimed as this build\'s');+});++test('an approval halt keeps the exact tokens out of the build journal and says them on the console: missing and stale', async () => {+ const cases = [+ ['missing', () => ({ rows: [commandRow(ROW, T, MD)] }), () => {}, (approvals) => ({ rows: new Set(), tables: new Set() }), 'command-state-approval-required'],+ ['stale at the preflight', () => ({ rows: [commandRow(ROW, T, MD)] }), (rows) => { rows[0]['@odata.etag'] = 'W/"1002"'; }, (approvals) => approvals, 'command-state-approval-stale'],+ ];+ for (const [what, setup, change, given, code] of cases) {+ const options = setup();+ const h = harness(options);+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ change(options.rows);+ const fresh = await h.approve(spec);+ const tokens = [...fresh.approvals.rows, ...fresh.approvals.tables, ...approvals.rows];+ const out = await buildWithJournal(h, spec, given(approvals));+ assert.strictEqual(out.caught && out.caught.code, code, what);+ assert.deepStrictEqual(h.org.writes(), [], `${what}: nothing written`);+ for (const token of tokens) {+ const digest = token.slice(token.lastIndexOf('/') + 1);+ assert.ok(!out.log.includes(digest), `${what}: no token digest in build-log.jsonl`);+ assert.ok(!out.status.includes(digest), `${what}: no token digest in build-status.json`);+ assert.ok(!out.caught.message.includes(digest), `${what}: nor in the halt's message`);+ }+ assert.match(out.log, new RegExp(code), `${what}: the journal still records the halt and its code`);+ assert.match(out.caught.message, /printed with this halt, and by a dry run/, `${what}: the message says where the tokens are`);+ for (const token of [...fresh.approvals.rows, ...fresh.approvals.tables].filter((tk) => !given(approvals).rows.has(tk) && !given(approvals).tables.has(tk))) {+ assert.ok(out.said.includes(`--authorize ${token}`), `${what}: the console shows ${token}`);+ assert.ok(out.caught.approvalDisplay.includes(`--authorize ${token}`), `${what}: a direct caller reads it on the halt`);+ }+ assert.deepStrictEqual(Object.keys(out.caught).filter((k) => /approval/i.test(k)), [], `${what}: the display is not enumerable`);+ }+});++test('a row that changes between the commands-phase read and its write halts stale with the new token on the console only', async () => {+ const rows = [commandRow(ROW, T, MD)];+ let armed = false;+ let reads = 0;+ // Read at the preflight, again before any write, then once more right before its own write: it changes at that last read.+ const overrides = (req) => {+ if (armed && req.method === 'GET' && req.path.startsWith(`/appactions(${ROW})`) && ++reads === 3) rows[0]['@odata.etag'] = 'W/"1003"';+ return undefined;+ };+ const h = harness({ rows, overrides });+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ armed = true;+ const out = await buildWithJournal(h, spec, approvals);+ assert.strictEqual(out.caught && out.caught.code, 'command-state-approval-stale', out.caught && out.caught.message);+ assert.match(out.caught.message, /the row changed since it was approved; it was not written/);+ assert.deepStrictEqual(h.org.writes(), []);+ const token = out.caught.approvalDisplay.match(/--authorize (\S+)/)[1];+ const digest = token.slice(token.lastIndexOf('/') + 1);+ assert.ok(!out.log.includes(digest) && !out.status.includes(digest) && !out.caught.message.includes(digest), 'the new token is not stored');+ assert.ok(out.said.includes(`--authorize ${token}`), 'and is said on the console');+});+// The design keeps ETags, digests, handlers and raw responses out of the feature's halts and journals. A refused read of the app is said by+// its status and Dataverse error code; the service's own message, which here carries a row version, is in neither the halt nor the journal.+test('a refused context read is said by its HTTP status and Dataverse code: the service\'s text and a version stay out of the halt and the journal', async () => {+ const SERVICE = 'planted-service-message W/"498763"';+ const refusal = () => json(403, { error: { code: '0x80040220', message: SERVICE } });+ for (const [what, arm, sent] of [+ // At the start of the build, before anything is sent.+ ['preflight', (h) => { h.armed = true; }, 0],+ // At the end of the build, after the row was written, acknowledged and read back and its table published.+ ['final', (h) => { h.armOnPublish = true; }, 1],+ ]) {+ const options = { rows: [commandRow(ROW, T, MD)] };+ const h = harness({+ ...options,+ onPublish: () => { if (h.armOnPublish) h.armed = true; },+ overrides: (req) => (h.armed && req.method === 'GET' && req.path.startsWith('/appmodules?') ? refusal() : undefined),+ });+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ arm(h);+ const out = await buildWithJournal(h, spec, approvals);+ assert.strictEqual(out.caught && out.caught.code, 'command-state-context-unverified', `${what}: ${out.caught && out.caught.message}`);+ assert.strictEqual(h.patches().length, sent, `${what}: PATCHes sent`);+ if (sent) assert.match(out.caught.message, /written by this build: the write was accepted and read back holding the declared flags/, what);+ assert.match(out.caught.message, /app 'contoso_Support': HTTP 403, Dataverse error 0x80040220; check that the signed-in account can read it/, what);+ for (const [where, text] of [['the halt', out.caught.message], ['build-log.jsonl', out.log], ['build-status.json', out.status], ['the console', out.said]]) {+ assert.ok(!text.includes('planted-service-message') && !text.includes('498763'), `${what}: ${where} holds no service text or version`);+ }+ assert.match(out.log, /command-state-context-unverified/, `${what}: the journal keeps the code`);+ }+});+test('with the feature off the journal and the console carry nothing of command states', async () => {+ const h = harness();+ const out = await buildWithJournal(h, specFor(null), undefined);+ assert.ifError(out.caught);+ assert.deepStrictEqual(h.org.requests, []);+ for (const [where, text] of [['build-log.jsonl', out.log], ['build-status.json', out.status], ['the console', out.said]]) {+ assert.doesNotMatch(text, /commandState|command-state|--authorize/, `${where} is unchanged by the feature`);+ }+});+// One history, one story: for each way a row ends unconfirmed in the commands phase, the halt the build stops with, the outcome it records+// and the line the CLI prints (build-model-app.js, through ROW_MESSAGES) say the same thing — whether this build wrote, what the earlier+// read showed, and what the last read found. The row changes at an exact read of it (armed after the dry run):+// read 1 is the preflight, 2 the commands-phase recheck, 3 the read right before its own write, then 4 the read after that write, and the+// read after every row's step is 4 for a row with nothing to write and 5 for one written.+test('the halt, the recorded outcome and the printed line agree on what happened to a row that ends unconfirmed', async () => {+ const { buildModelApp } = require('../build-model-app.js');+ const { makeTempDir } = require('./helpers/temp-dirs.js');+ const UNCHANGED = 'not written by this build (it already held the declared flags)';+ const ACKNOWLEDGED = 'written by this build: the write was accepted and read back holding the declared flags';+ const OBSERVED = 'this build\'s write got no usable answer (HTTP 503), so its outcome is unknown; a later read found the declared flags, which is not proof this build saved them';+ const DRIFT = 'then a read after every row\'s step found hidden false, disabled false, not the declared flags';+ const LOST = 'this build\'s write got no usable answer (HTTP 503), so its outcome is unknown; then a read after its write found hidden false, disabled false, not the declared flags';+ const cases = [+ { what: 'unchanged, then changed', hidden: true, loseAt: 4, patches: 0, code: 'command-state-not-confirmed', outcome: 'drifted', before: 'unchanged', history: `${UNCHANGED}; ${DRIFT}` },+ { what: 'written and read back, then changed', hidden: false, loseAt: 5, patches: 1, code: 'command-state-not-confirmed', outcome: 'drifted', before: 'acknowledged', history: `${ACKNOWLEDGED}; ${DRIFT}` },+ { what: 'unanswered, matched by someone else, then changed', hidden: false, loseAt: 5, competing: true, patches: 1, code: 'command-state-not-confirmed', outcome: 'drifted', before: 'observed-matching-after-unknown-send', history: `${OBSERVED}; ${DRIFT}` },+ { what: 'unanswered, and never seen holding the flags', hidden: false, lost: true, patches: 1, code: 'command-state-write-unknown', outcome: 'unknown', history: LOST },+ ];+ for (const c of cases) {+ const rows = [commandRow(ROW, T, MD, { hidden: c.hidden })];+ let armed = false;+ let reads = 0;+ const seen = [];+ const overrides = (req) => {+ if (!armed) return undefined;+ if (req.method === 'PATCH' && (c.competing || c.lost)) {+ // Answered 503 and never stored; for `competing`, someone else sets the same flag at a new version first.+ if (c.competing) { rows[0].hidden = true; rows[0]['@odata.etag'] = 'W/"1500"'; }+ return json(503, { error: { code: '0x80072321', message: 'unavailable' } });+ }+ if (req.method === 'GET' && req.path.startsWith(`/appactions(${ROW})`)) {+ if (++reads === c.loseAt) { rows[0].hidden = false; rows[0]['@odata.etag'] = 'W/"1600"'; }+ seen.push(rows[0].hidden);+ }+ return undefined;+ };+ const h = harness({ rows, overrides });+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ armed = true;+ const lines = [];+ let halt;+ try {+ const { sdk } = h.mockSdk();+ await buildModelApp(spec, { apply: true, publish: true, env: ORIGIN, workspaceDir: makeTempDir('cs-agree-'), commandStateApprovals: approvals }, {+ sdk, log: (m) => lines.push(String(m)), warn: (m) => lines.push(String(m)), sleep: async () => {},+ runBuild: (s, o) => runSdkBuild(s, { ...o, commandStateTransport: h.transport }),+ });+ } catch (error) {+ halt = error;+ }+ assert.strictEqual(halt && halt.code, c.code, `${c.what}: ${halt && halt.message}`);+ assert.strictEqual(h.patches().length, c.patches, `${c.what}: PATCHes sent`);+ const row = halt.commandStates.rows[0];+ assert.deepStrictEqual([row.outcome, row.before], [c.outcome, c.before], `${c.what}: the recorded outcome keeps the history`);+ const line = lines.find((l) => l.startsWith(` command state ${T}/MainTab/${ROW}: `));+ assert.ok(line, `${c.what}: the CLI printed the row`);+ assert.ok(line.startsWith(` command state ${T}/MainTab/${ROW}: ${c.outcome}${c.before ? ` after ${c.before}` : ''}`), `${c.what}: ${line}`);+ assert.ok(line.endsWith(` — ${c.history}`), `${c.what}: the line says the history: ${line}`);+ // The halt says the same history, from the same facts, then its remedy.+ assert.ok(halt.message.includes(`: ${c.history} — `) || halt.message.includes(`: ${c.history}; the row is still at the version`), `${c.what}: ${halt.message}`);+ if (c.before) {+ assert.ok(seen.includes(true), `${c.what}: an exact read did hold the declared flags`);+ } else {+ assert.ok(!seen.includes(true), `${c.what}: no read held the declared flags`);+ }+ for (const text of [halt.message, line]) {+ if (c.before !== 'acknowledged') assert.doesNotMatch(text.replace('not proof this build saved them', ''), /accept|acknowledg|sav(e|ed|ing)\b|(?<!not )written by this build/i, `${c.what}: ${text}`);+ if (c.before === 'unchanged') assert.doesNotMatch(text, /this build's write|this build sent|the write of/i, `${c.what}: no write invented: ${text}`);+ if (c.before) assert.doesNotMatch(text, /no read (after it )?showed/, `${c.what}: the matching read is not denied: ${text}`);+ }+ }+});+// One apply through the build's own entry (buildModelApp), counting its attempts. `retry` fails the app's create once with a 503 after the+// row step, so the build runs a second attempt; `atRetry` runs at that moment (before the second attempt reads anything).+async function throughBuild({ hidden = false, overrides, retry = false, atRetry, onPublish } = {}) {+ const { buildModelApp } = require('../build-model-app.js');+ const { makeTempDir } = require('./helpers/temp-dirs.js');+ const rows = [commandRow(ROW, T, MD, { hidden })];+ let armed = false;+ const h = harness({ rows, overrides: (req) => (armed && overrides ? overrides(req, rows) : undefined), onPublish: (tables) => { if (onPublish) onPublish(rows, tables); } });+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ armed = true;+ const { sdk } = h.mockSdk();+ if (retry) {+ const create = sdk.createArtifact;+ let failed = false;+ sdk.createArtifact = (...args) => {+ if (args[0] === 'app' && !failed) {+ failed = true;+ if (atRetry) atRetry(rows);+ throw Object.assign(new Error('injected service failure'), { statusCode: 503 });+ }+ return create(...args);+ };+ }+ const lines = [];+ let attempts = 0;+ let result;+ let halt;+ try {+ result = await buildModelApp(spec, { apply: true, publish: true, env: ORIGIN, workspaceDir: makeTempDir('cs-facts-'), commandStateApprovals: approvals }, {+ sdk, log: (m) => lines.push(String(m)), warn: (m) => lines.push(String(m)), sleep: async () => {},+ runBuild: (s, o) => { attempts += 1; return runSdkBuild(s, { ...o, commandStateTransport: h.transport }); },+ });+ } catch (error) {+ halt = error;+ }+ const states = (halt || result).commandStates;+ const line = lines.find((l) => l.startsWith(` command state ${T}/MainTab/${ROW}: `));+ return { h, halt, result, row: states.rows[0], states, line, lines, attempts, rows };+}+const NO_CLAIM = /accept|acknowledg|\bsav(e|es|ed|ing)\b|(?<!not )written by this build/i;+const unproven = (text) => text.replaceAll('not proof this build saved them', '');++test('a read after every row\'s step that cannot be judged is said as unreadable: never as flags the row does not hold', async () => {+ let reads = 0;+ // Reads in the apply: preflight, recheck, own step, read back after the write, then the read after every row's step (the fifth).+ const out = await throughBuild({+ overrides: (req) => {+ if (req.method === 'GET' && req.path.startsWith(`/appactions(${ROW})`) && ++reads === 5) return json(403, { error: { code: '0x80040220', message: 'denied' } });+ return undefined;+ },+ });+ assert.strictEqual(out.halt && out.halt.code, 'command-state-not-confirmed', out.halt && out.halt.message);+ assert.strictEqual(out.h.patches().length, 1);+ assert.match(out.halt.message, /; then the row could not be read and judged after every row's step \(command-state-[a-z-]+\)/);+ const publication = out.halt.commandStatePublicationError;+ assert.ok(publication, 'the table is reported unpublished');+ assert.match(publication.message, /could not be read at its last read/);+ for (const text of [out.halt.message, out.line, publication.message]) {+ assert.doesNotMatch(text, /did not hold|does not hold|other flags|found hidden/, text);+ }+});++test('a retry of the build keeps the write its earlier attempt sent: never "not written by this build", never sent again', async () => {+ const cases = [+ { what: 'the row still holds the flags', ok: true, outcome: 'acknowledged' },+ {+ what: 'the row changes before the final proof', code: 'command-state-not-confirmed', outcome: 'acknowledged',+ // The table is published in each attempt; the change comes with the second attempt's publication, after its reads.+ onPublish: ((n) => (rows) => { if (++n === 2) { rows[0].hidden = false; rows[0]['@odata.etag'] = 'W/"2002"'; } })(0),+ said: /then a read at the end of the build found hidden false, disabled false, not the declared flags \(attempt 2\)/,+ },+ {+ what: 'the row changes before the second attempt reads it', code: 'command-state-approval-stale',+ atRetry: (rows) => { rows[0].hidden = false; rows[0]['@odata.etag'] = 'W/"2003"'; },+ said: /an earlier attempt of this build already sent a write: command state new_ticket\/MainTab\/[0-9a-f-]+: written by this build: the write was accepted and read back holding the declared flags \(attempt 1\)/,+ },+ ];+ for (const c of cases) {+ const out = await throughBuild({ retry: true, atRetry: c.atRetry, onPublish: c.onPublish });+ assert.strictEqual(out.attempts, 2, c.what);+ assert.strictEqual(out.h.patches().length, 1, `${c.what}: one PATCH, in the first attempt`);+ if (c.ok) assert.ifError(out.halt);+ else assert.strictEqual(out.halt && out.halt.code, c.code, `${c.what}: ${out.halt && out.halt.message}`);+ if (c.outcome) assert.strictEqual(out.row.outcome === 'drifted' ? out.row.before : out.row.outcome, c.outcome, c.what);+ assert.ok(out.line, `${c.what}: the CLI printed the row`);+ for (const text of [out.line, ...(out.halt ? [out.halt.message] : [])]) {+ assert.doesNotMatch(text, /not written by this build/, `${c.what}: ${text}`);+ assert.match(text, /written by this build: the write was accepted and read back holding the declared flags \(attempt 1\)/, `${c.what}: ${text}`);+ }+ if (c.said) assert.match(out.halt.message, c.said, c.what);+ // A row's facts carry what was read and sent, never a version, a token or the service's text.+ const facts = JSON.stringify(out.row.facts);+ assert.ok(out.row.facts.length > 0, c.what);+ assert.doesNotMatch(facts, /W\/"|etag|version|token|approval|message/i, c.what);+ }+});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/command-state-contract.test.js b/plugins/model-apps/scripts/tests/command-state-contract.test.jsnew file mode 100644index 000000000..3168eb03a--- /dev/null+++ b/plugins/model-apps/scripts/tests/command-state-contract.test.js@@ -0,0 +1,129 @@+'use strict';+// The offline contract of commandStates (lib/command-state-contract.js): what a spec may say, the one form the build uses, and the exact+// approvals that let a build change a row or publish its table.++const test = require('node:test');+const assert = require('node:assert');+const C = require('../lib/command-state-contract.js');+const { validateAppSpec } = require('../lib/app-spec.js');++const ROW = '11111111-1111-4111-8111-111111111111';+const ROW2 = '22222222-2222-4222-8222-222222222222';+const ORIGIN = 'https://contoso.crm.dynamics.com';+const APP = '33333333-3333-4333-8333-333333333333';+const TABLE = '44444444-4444-4444-8444-444444444444';++const spec = (states, extra = {}) => ({+ minimumPluginVersion: '2.24.0',+ app: { uniqueName: 'new_app', displayName: 'App' },+ entities: [{ schemaName: 'new_Ticket', displayName: 'Ticket' }],+ commandStates: states,+ ...extra,+});+const entry = (extra = {}) => ({ entity: 'new_ticket', location: 'MainTab', scope: 'table', rowId: ROW, hidden: true, ...extra });+const findings = (s) => C.validateCommandStates(s).findings.map((f) => [f.code, f.subreason, f.path]);++test('a well-formed entry has no findings; absent or empty commandStates is not checked at all', () => {+ assert.deepStrictEqual(findings(spec([entry()])), []);+ assert.deepStrictEqual(findings(spec([entry({ hidden: undefined, disabled: false })].map(({ hidden, ...e }) => e))), []);+ assert.deepStrictEqual(findings({ app: {} }), []);+ assert.deepStrictEqual(findings({ commandStates: [] }), [], 'an empty list asks for nothing and needs no version floor');+ assert.strictEqual(C.usesCommandStates(spec([])), false);+ assert.strictEqual(C.usesCommandStates(spec([entry()])), true);+});++test('every field is closed and exact: unknown keys, bars, scopes, booleans and row ids are refused with a stable code', () => {+ const s = spec([+ entry({ isdisabled: true, label: 'x' }),+ entry({ rowId: ROW2, location: 'maintab' }),+ entry({ rowId: `{${ROW2}}` }),+ entry({ rowId: '00000000-0000-0000-0000-000000000000', hidden: 'yes' }),+ entry({ rowId: ROW.toUpperCase(), scope: 'Table' }),+ { entity: 'new_other', location: 'Grid', scope: 'table', rowId: '55555555-5555-4555-8555-555555555555' },+ 'x',+ ]);+ assert.deepStrictEqual(findings(s), [+ ['command-state-spec-invalid', 'unknown-field', 'commandStates[0].isdisabled'],+ ['command-state-spec-invalid', 'unknown-field', 'commandStates[0].label'],+ ['command-state-spec-invalid', 'location-invalid', 'commandStates[1].location'],+ ['command-state-spec-invalid', 'row-id-invalid', 'commandStates[2].rowId'],+ ['command-state-spec-invalid', 'row-id-invalid', 'commandStates[3].rowId'],+ ['command-state-spec-invalid', 'boolean-required', 'commandStates[3].hidden'],+ ['command-state-spec-invalid', 'scope-invalid', 'commandStates[4].scope'],+ ['command-state-spec-invalid', 'row-id-duplicate', 'commandStates[4].rowId'],+ ['command-state-spec-invalid', 'entity-undeclared', 'commandStates[5].entity'],+ ['command-state-spec-invalid', 'location-invalid', 'commandStates[5].location'],+ ['command-state-spec-invalid', 'flags-required', 'commandStates[5]'],+ ['command-state-spec-invalid', 'object-required', 'commandStates[6]'],+ ]);+ assert.match(C.validateCommandStates(s).errors[0], /^command-state-spec-invalid: commandStates\[0\]\.isdisabled \(unknown-field\): .*use disabled/);+ assert.deepStrictEqual(findings(spec('x')), [['command-state-spec-invalid', 'array-required', 'commandStates']]);+});++test('scope "app" is refused as unverified in this version, not as a typo', () => {+ assert.deepStrictEqual(findings(spec([entry({ scope: 'app' })])), [['command-state-app-scope-unverified', null, 'commandStates[0].scope']]);+});++test('the spec must name its app and require 2.24.0 or newer, so an older plugin refuses it instead of ignoring it', () => {+ assert.deepStrictEqual(findings(spec([entry()], { minimumPluginVersion: '2.23.9', app: {} })), [+ ['command-state-spec-invalid', 'app-unique-name-required', 'app.uniqueName'],+ ['command-state-spec-invalid', 'version-floor-required', 'minimumPluginVersion'],+ ]);+ assert.deepStrictEqual(findings(spec([entry()], { minimumPluginVersion: '2.25.0' })), []);+ assert.deepStrictEqual(findings(spec([entry()], { minimumPluginVersion: undefined })).map((f) => f[1]), ['version-floor-required']);+});++test('validateAppSpec reports the findings as errors, and as warnings for the structural profile', () => {+ const bad = spec([entry({ scope: 'app' })]);+ const strict = validateAppSpec(bad);+ assert.ok(strict.errors.some((e) => e.startsWith('command-state-app-scope-unverified: commandStates[0].scope')), strict.errors.join('\n'));+ const structural = validateAppSpec(bad, { profile: 'structural' });+ assert.ok(!structural.errors.some((e) => e.startsWith('command-state-')));+ assert.ok(structural.warnings.some((e) => e.startsWith('command-state-app-scope-unverified')));+});++test('normalize lower-cases names and ids, maps the bar to its location, and keeps only the flags the entry sets, by column name', () => {+ const s = spec([entry({ entity: 'New_Ticket', rowId: ROW.toUpperCase().replace('-4111', '-4111'), disabled: false }), entry({ rowId: ROW2, location: 'ContextualTab', hidden: undefined })]);+ delete s.commandStates[1].hidden;+ s.commandStates[1].disabled = true;+ assert.deepStrictEqual(C.normalizeCommandStates(s), [+ { entity: 'new_ticket', bar: 'MainTab', location: 0, scope: 'table', rowId: ROW, desired: { hidden: true, isdisabled: false } },+ { entity: 'new_ticket', bar: 'ContextualTab', location: 2, scope: 'table', rowId: ROW2, desired: { isdisabled: true } },+ ]);+ assert.deepStrictEqual(C.normalizeCommandStates(spec([])), []);+ assert.deepStrictEqual(C.diffCommandFlags({ hidden: false, isdisabled: true }, { hidden: true, isdisabled: true }), { hidden: false }, 'false is an instruction, an equal flag is not sent');+ assert.deepStrictEqual(C.diffCommandFlags({}, { hidden: true, isdisabled: true }), {});+});++test('a row approval names one version of one row under one intent in one environment; a table approval names the table only', () => {+ const base = { origin: ORIGIN, appId: APP, tableId: TABLE, entity: 'new_ticket', location: 0, rowId: ROW, ifMatch: 'W/"1001"', desired: { hidden: true } };+ const key = C.commandStateApprovalKey(base);+ assert.match(key, new RegExp(`^overwrite:command-state:new_ticket/MainTab/${ROW}/[0-9a-f]{64}$`));+ assert.strictEqual(C.commandStateApprovalKey({ ...base, origin: 'HTTPS://CONTOSO.crm.dynamics.com/main.aspx', entity: 'NEW_TICKET', appId: APP.toUpperCase() }), key, 'the same row and intent spelled differently is the same approval');+ for (const change of [{ ifMatch: 'W/"1002"' }, { origin: 'https://fabrikam.crm.dynamics.com' }, { desired: { hidden: false } }, { desired: { hidden: true, isdisabled: false } }, { appId: ROW2 }, { tableId: ROW2 }, { location: 1 }]) {+ assert.notStrictEqual(C.commandStateApprovalKey({ ...base, ...change }), key, JSON.stringify(change));+ }+ const table = C.commandTablePublishApprovalKey(base);+ assert.match(table, /^publish:command-state-table:new_ticket\/[0-9a-f]{64}$/);+ assert.strictEqual(C.commandTablePublishApprovalKey({ ...base, ifMatch: 'W/"9"', rowId: ROW2 }), table, 'publishing is per table, whatever row changed');+ assert.notStrictEqual(C.commandTablePublishApprovalKey({ ...base, tableId: ROW2 }), table);+});++test('authorization keys: both token families are claimed; a malformed or undeclared one is a problem, never passed on as another feature\u2019s', () => {+ const s = spec([entry()]);+ const row = C.commandStateApprovalKey({ origin: ORIGIN, appId: APP, tableId: TABLE, entity: 'new_ticket', location: 0, rowId: ROW, ifMatch: 'W/"1"', desired: { hidden: true } });+ const table = C.commandTablePublishApprovalKey({ origin: ORIGIN, appId: APP, tableId: TABLE, entity: 'new_ticket' });+ const otherRow = row.replace(ROW, ROW2);+ const otherTable = table.replace('new_ticket', 'new_other');+ const r = C.commandStateAuthorizationKeys([row, table, 'overwrite:view:new_ticket/x', otherRow, otherTable, 'OVERWRITE:command-state:new_ticket/MainTab/*', `${table}0`], s);+ assert.deepStrictEqual([...r.rows], [row]);+ assert.deepStrictEqual([...r.tables], [table]);+ assert.deepStrictEqual(r.rest, ['overwrite:view:new_ticket/x']);+ assert.strictEqual(r.problems.length, 4, r.problems.join('\n'));+ assert.match(r.problems[0], /no commandStates entry declares/);+ assert.match(r.problems[1], /no commandStates entry declares/);+ assert.match(r.problems[2], /exactly as the build prints it/);+ // A spec with no (valid) command states claims the tokens and accepts none of them.+ const none = C.commandStateAuthorizationKeys([row, table, 'x'], { commandStates: [{}] });+ assert.deepStrictEqual([none.rows.size, none.tables.size, none.rest, none.problems.length], [0, 0, ['x'], 2]);+});diff --git a/plugins/model-apps/scripts/tests/command-state-outcomes.test.js b/plugins/model-apps/scripts/tests/command-state-outcomes.test.jsnew file mode 100644index 000000000..6d83705fc--- /dev/null+++ b/plugins/model-apps/scripts/tests/command-state-outcomes.test.js@@ -0,0 +1,330 @@+'use strict';+// What the command-state writer (lib/command-state-run.js) says about a row after its step, and the outcome it records for it.+// - Every message words a row from its FACTS (each read and what it found, each write and how it was answered), through one renderer+// (renderRowHistory) and one publication kind (rowKind). The table below builds every history of facts the writer can produce — no write,+// an answered, unanswered or refused write; each read after it matched, other or unreadable; a later read; a retry of the build — and+// checks every message path says what those facts show and nothing more.+// - ROW_OUTCOMES is closed and checked against the facts at run time: `record` is the one boundary a row's outcome is set through, and+// checkRowRecord throws on a value the list does not name, or one the row's facts do not show.+// - The wording inventory is a case-insensitive literal-text inventory: it reads every string, template and regular-expression literal of+// the writer's sources with the plugin's own lexer (lib/source-literals.js), whatever the quotes, and fails where one says a listed claim+// word (accept, acknowledge, save, outcome unknown, written by this build, each with the inflections CLAIM_WORDS lists) outside the one+// vocabulary. It reads literal text only — no constant folding or call-graph analysis — so it is backed by the behavioural tests above,+// which check the actual messages, a real halt that sent nothing among them.++const test = require('node:test');+const assert = require('node:assert');+const fs = require('node:fs');+const path = require('node:path');+const Module = require('node:module');+const { blankLiterals, commentRanges } = require('../lib/source-literals.js');+const LIB = path.join(__dirname, '..', 'lib', 'command-state-run.js');+const { ROW_OUTCOMES, DRIFT_BEFORE, ROW_MESSAGES, renderRowHistory, checkRowRecord, createCommandStatePublicationObserver } = require(LIB);++const read = (result, phase, attempt = 1) => ({+ attempt, kind: 'read', phase, result, ...(result === 'unreadable' ? { code: 'command-state-row-unreadable' } : { hidden: result === 'matched', disabled: false }),+});+const send = (answer, status, attempt = 1) => ({ attempt, kind: 'send', answer, ...(status === undefined ? {} : { status }), flags: { hidden: true } });+const BEFORE_SEND = [read('differed', 'preflight'), read('differed', 'recheck'), read('differed', 'own-step')];++// Every history of facts the writer can record for a row, named.+function histories() {+ const out = [];+ const LATER = [null, 'matched', 'differed', 'unreadable'];+ const RETRY = {+ none: [],+ 'retry, held': [read('matched', 'preflight', 2), read('matched', 'recheck', 2), read('matched', 'own-step', 2), read('matched', 'after-every-row', 2), read('matched', 'final', 2)],+ 'retry, changed': [read('differed', 'preflight', 2)],+ 'retry, unreadable': [read('unreadable', 'preflight', 2)],+ };+ for (const [retry, tail] of Object.entries(RETRY)) {+ for (const step of ['matched', 'differed', 'unreadable']) {+ for (const later of LATER) {+ const after = later ? [read(later, 'after-every-row')] : [];+ out.push({ name: `no write, own step ${step}, later ${later}, ${retry}`, facts: [read(step, 'preflight'), read(step, 'own-step'), ...after, ...tail] });+ for (const [what, s] of [['answered 204', send('acknowledged', 204)], ['no answer', send('lost')], ['answered 503', send('lost', 503)]]) {+ out.push({ name: `${what}, read back ${step}, later ${later}, ${retry}`, facts: [...BEFORE_SEND, s, read(step, 'readback'), ...after, ...tail] });+ }+ }+ }+ out.push({ name: `refused, ${retry}`, facts: [...BEFORE_SEND, send('refused', 403), ...tail] });+ out.push({ name: `never reached, ${retry}`, facts: [...tail] });+ }+ return out;+}++// What a history's facts alone establish, computed here from the facts, not by the writer.+function establish(facts) {+ const reads = facts.filter((e) => e.kind === 'read');+ const counted = facts.filter((e) => e.kind === 'send' && e.answer !== 'refused');+ const readBackAfterAck = facts.some((e, i) => e.kind === 'send' && e.answer === 'acknowledged' && facts[i + 1] && facts[i + 1].phase === 'readback' && facts[i + 1].result === 'matched');+ const firstSend = facts.findIndex((e) => e.kind === 'send');+ const narrated = firstSend < 0 ? reads : facts.slice(firstSend).filter((e) => e.kind === 'read');+ return {+ readBackAfterAck,+ sent: counted.length > 0,+ differedSaid: narrated.some((e) => e.result === 'differed'),+ unreadableSaid: narrated.some((e) => e.result === 'unreadable'),+ last: narrated[narrated.length - 1] || null,+ multi: new Set(facts.map((e) => e.attempt)).size > 1,+ };+}++// The claim words: a row was accepted, acknowledged or saved, or written by this build, in any case (each word's inflections listed).+const CLAIM = /accept|acknowledg|\bsav(?:e|es|ed|ing)\b|(?<!not )written by this build/i;+const unclaimed = (text) => text.replaceAll('which is not proof this build saved them', '').replaceAll('not proof this build saved them', '');+const row = (facts) => ({ entity: 'new_a', location: 'MainTab', scope: 'table', rowId: 'r1', outcome: 'unknown', changed: [], facts });+const publicationOf = (r) => {+ const o = createCommandStatePublicationObserver();+ o.register('new_a', []);+ o.trackRows(() => [r]);+ const error = new Error('halted');+ o.attachFailure(error);+ return error.commandStatePublicationError.message.split(' — ')[0];+};++test('every history of facts is worded by every message path from those facts, and says only what they show', () => {+ const all = histories();+ assert.ok(all.length > 150, `the table covers the histories (${all.length})`);+ for (const { name, facts } of all) {+ const known = establish(facts);+ const r = row(facts);+ const history = renderRowHistory(facts);+ // One renderer: every row-level path carries the same history, whole.+ assert.strictEqual(ROW_MESSAGES.postWriteMismatch(r), `command state new_a/MainTab/r1: ${history}`, name);+ assert.ok(ROW_MESSAGES.finalDrift(r).includes(`: ${history} — `), name);+ assert.ok(ROW_MESSAGES.lateNote([r]).includes(`: ${history})`), name);+ assert.ok(ROW_MESSAGES.resultLine(r).endsWith(` — ${history}`), name);+ // Accepted, saved, or written by this build: only for a write answered 200/204 and then read back holding the flags.+ assert.strictEqual(CLAIM.test(unclaimed(history)), known.readBackAfterAck, `${name}: ${history}`);+ // A write of this build is mentioned exactly when one was sent and may have landed; otherwise the row was not written by this build.+ assert.strictEqual(/this build's write|(?<!not )written by this build/.test(history), known.sent, `${name}: ${history}`);+ assert.strictEqual(/not written by this build/.test(history), !known.sent, `${name}: ${history}`);+ // Other flags are said only of a read that found them; an unreadable read is said as unreadable, never as flags found or absent.+ assert.strictEqual(/found hidden/.test(history), known.differedSaid, `${name}: ${history}`);+ assert.strictEqual(/could not be read and judged/.test(history), known.unreadableSaid, `${name}: ${history}`);+ // The history ends with what the last read found.+ const end = history.replace(/ \(attempt \d+\)$/, '');+ if (known.last && known.last.result === 'unreadable') assert.match(end, /could not be read and judged [^;]* \(command-state-row-unreadable\)\)?$/, `${name}: ${history}`);+ if (known.last && known.last.result === 'differed') assert.match(end, /found hidden false, disabled false, not the declared flags\)?$/, `${name}: ${history}`);+ if (known.last && known.last.result === 'matched') assert.match(end, /declared flags\)?$|not proof this build saved them$/, `${name}: ${history}`);+ // A retry of the build says which attempt each clause is from; a single attempt does not.+ assert.strictEqual(/\(attempt \d+\)/.test(history), known.multi, `${name}: ${history}`);+ // The publication's words for the table: "saved" only for a write read back holding the flags, and never flags a read did not find.+ const table = publicationOf(r);+ if (CLAIM.test(unclaimed(table))) assert.ok(known.readBackAfterAck, `${name}: ${table}`);+ if (/other flags/.test(table)) assert.ok(known.last && known.last.result === 'differed', `${name}: ${table}`);+ if (/could not be read/.test(table)) assert.ok(known.last && known.last.result === 'unreadable', `${name}: ${table}`);+ assert.doesNotMatch(table, /did not hold|does not hold/, `${name}: ${table}`);+ if (known.last && known.last.result === 'unreadable') assert.doesNotMatch(table, /other flags|already held|saved, not/, `${name}: ${table}`);+ if (!known.sent) assert.doesNotMatch(table, /write outcome unknown|after a write/, `${name}: ${table}`);+ }+ // A row with no facts at all claims neither a write nor a read.+ for (const odd of [{ outcome: 'acknowledged' }, { outcome: 'something-new' }]) {+ const text = ROW_MESSAGES.lateNote([{ entity: 'new_a', location: 'MainTab', rowId: 'r1', ...odd }]);+ assert.match(text, /what this build did to it is not known/);+ assert.doesNotMatch(text, /accept|acknowledg|sav(e|ed)\b|write|read (back|found|showed)/i);+ }+});++test('the outcome a row is recorded with is one its facts show, and exactly one step outcome fits any facts', () => {+ const STEP = ['unchanged', 'acknowledged', 'observed-matching-after-unknown-send', 'unknown'];+ const fits = (outcome, facts, before) => { try { checkRowRecord({ outcome, ...(before ? { before } : {}) }, facts); return true; } catch { return false; } };+ for (const { name, facts } of histories()) {+ const known = establish(facts);+ const ok = STEP.filter((o) => fits(o, facts));+ const reads = facts.filter((e) => e.kind === 'read');+ const last = reads[reads.length - 1];+ if (fits('acknowledged', facts)) assert.ok(facts.some((e) => e.answer === 'acknowledged') && last.result === 'matched', name);+ if (fits('observed-matching-after-unknown-send', facts)) assert.ok(facts.some((e) => e.answer === 'lost') && last.result === 'matched', name);+ if (fits('unchanged', facts)) assert.ok(!known.sent && last.result === 'matched', name);+ if (fits('unknown', facts)) assert.ok(known.sent, name);+ assert.ok(ok.length <= 1, `${name}: ${ok}`);+ if (known.sent) assert.strictEqual(ok.length, 1, `${name}: a sent write always has one step outcome`);+ for (const before of DRIFT_BEFORE) if (fits('drifted', facts, before)) assert.notStrictEqual(last.result, 'matched', name);+ }+ const ack = [...BEFORE_SEND, send('acknowledged', 204), read('matched', 'readback')];+ const lost = [...BEFORE_SEND, send('lost', 503), read('matched', 'readback')];+ for (const [outcome, facts, before] of [+ ['acknowledged', [...BEFORE_SEND, send('acknowledged', 204), read('differed', 'readback')]],+ ['acknowledged', lost],+ ['unchanged', lost],+ ['unchanged', [read('differed', 'own-step')]],+ ['observed-matching-after-unknown-send', [...BEFORE_SEND, send('lost')]],+ ['unknown', ack],+ ['unknown', [read('differed', 'own-step')]],+ ['refused', ack],+ ['drifted', ack, 'acknowledged'],+ ['drifted', [...ack, read('unreadable', 'after-every-row')], 'unchanged'],+ ['drifted', [...lost, read('differed', 'after-every-row')], 'acknowledged'],+ ]) {+ assert.throws(() => checkRowRecord({ outcome, ...(before ? { before } : {}) }, facts), (e) => e instanceof TypeError && /is not what the row's facts show/.test(e.message), `${outcome} ${before || ''}`);+ }+ assert.strictEqual(checkRowRecord({ outcome: 'drifted', before: 'acknowledged' }, [...ack, read('unreadable', 'after-every-row')]).before, 'acknowledged');+ assert.strictEqual(checkRowRecord({ outcome: 'refused' }, [...BEFORE_SEND, send('refused', 412)]).outcome, 'refused');+});++test('a row outcome is recorded only through checkRowRecord, which refuses any value the closed list does not name', () => {+ for (const outcome of ROW_OUTCOMES.filter((o) => o !== 'planned' && o !== 'drifted')) assert.strictEqual(checkRowRecord({ outcome }).outcome, outcome);+ for (const before of DRIFT_BEFORE) assert.strictEqual(checkRowRecord({ outcome: 'drifted', before }).before, before);+ const computed = ['send', 'lost'].join('-');+ for (const bad of [{ outcome: "send-lost" }, { outcome: computed }, { outcome: undefined }, {}, { outcome: 'planned' },+ { outcome: 'drifted' }, { outcome: 'drifted', before: 'unknown' }, { outcome: 'unknown', before: 'acknowledged' }]) {+ assert.throws(() => checkRowRecord(bad), (e) => e instanceof TypeError && /command-state writer defect/.test(e.message), JSON.stringify(bad));+ }+ // And the writer has no other way to set one: `record` passes every patch and the row's facts through it, and nothing else assigns a row+ // result's outcome.+ // A Windows checkout can give the source CRLF line endings (git core.autocrlf), and the shape below is matched line by line.+ const code = blankLiterals(fs.readFileSync(LIB, 'utf8').replace(/\r\n/g, '\n'));+ assert.match(code, /const record = \(rowId, patch\) => \{\n\s+const row = results\.get\(rowId\);\n\s+checkRowRecord\(patch, row\.facts\);\n[\s\S]{0,400}?return Object\.assign\(row, patch\);\n\s+\};/);+ assert.strictEqual((code.match(/Object\.assign\(/g) || []).length, 1);+ assert.strictEqual((code.match(/checkRowRecord\(/g) || []).length, 2, 'its definition and the one call in record');+ assert.deepStrictEqual([...code.matchAll(/(\w+)\.outcome\s*=(?!=)/g)].map((m) => m[1]).filter((who) => who !== 'entry'), [], 'only a table entry\'s outcome is assigned');+ // A row's facts only grow, through `note`: nothing else adds to, replaces or empties them.+ assert.strictEqual((code.match(/\.facts\.push\(/g) || []).length, 1);+ assert.doesNotMatch(code, /\.facts\s*=(?!=)|facts\.(splice|pop|shift|length\s*=)/);+});++// The writer, compiled from `source` in place of the file (its own folder, so its requires resolve), without touching the module cache.+function writerFrom(source) {+ const m = new Module(LIB, module);+ m.filename = LIB;+ m.paths = Module._nodeModulePaths(path.dirname(LIB));+ m._compile(source, LIB);+ return m.exports;+}++const T = 'new_ticket';+const MD = '44444444-4444-4444-8444-444444444444';+const ROW = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';+// One row through a writer's own steps against the fake org (a real raw client and the feature's transport): preflight, recheck, apply,+// then — when `drift` — the build's publication answered ok, the row changed, and the final proof.+async function throughWriter(writer, { hidden = false, patch, drift = false } = {}) {+ const { createAzHttpClient } = require('../lib/sdk-http-client.js');+ const { createCommandStateTransport, commandStateSendOnce } = require('../lib/command-state-transport.js');+ const { createCommandStateOrg, commandRow, ORIGIN } = require('./helpers/command-state-org.js');+ const spec = { app: { name: 'Support', uniqueName: 'contoso_Support' }, commandStates: [{ entity: T, location: 'MainTab', scope: 'table', rowId: ROW, hidden: true }] };+ const rows = [commandRow(ROW, T, MD, { hidden })];+ const org = createCommandStateOrg({ writable: true, tables: { [T]: { metadataId: MD } }, rows, overrides: (req) => (req.method === 'PATCH' && patch ? patch() : undefined) });+ const client = createAzHttpClient(ORIGIN, { getToken: () => 'test-token', request: org.request, sleep: async () => {}, sendOnce: commandStateSendOnce });+ const transport = createCommandStateTransport({ client, apiUrl: (p) => `${ORIGIN}/api/data/v9.2${p}` });+ const plan = await writer.createCommandStateRun({ spec, transport, origin: ORIGIN }).plan();+ const approvals = { rows: new Set(plan.rows.map((r) => r.approval).filter(Boolean)), tables: new Set(plan.tables.map((t) => t.token)) };+ const observer = writer.createCommandStatePublicationObserver();+ const run = writer.createCommandStateRun({ spec, transport, origin: ORIGIN, approvals, observer });+ await run.preflight();+ await run.recheckAll();+ await run.applyRows();+ if (!drift) return { org, run };+ observer.observePlain([T], { ok: true });+ rows[0].hidden = false;+ rows[0]['@odata.etag'] = 'W/"2000"';+ await run.assertComplete();+ return { org, run };+}++test('a writer that would record an outcome the list does not name, or its facts do not show, stops at the record', async () => {+ const { json } = require('./helpers/command-state-org.js');+ const source = fs.readFileSync(LIB, 'utf8');+ const lostSend = "record(item.rowId, { outcome: 'unknown', changed, code: CODES.writeUnknown });";+ assert.ok(source.includes(lostSend), 'the lost-send record this mutates is still in the writer');+ // The PATCH is answered 503 and never stored, so the read after it does not show the flags: the lost-send record.+ const lose = () => json(503, { error: { code: '0x80072321', message: 'unavailable' } });+ await assert.rejects(throughWriter(writerFrom(source), { patch: lose }), (e) => e.code === 'command-state-write-unknown', 'the writer as shipped records unknown and halts');+ for (const [what, mutated, said] of [+ ['a double-quoted literal', source.replace(lostSend, 'record(item.rowId, { outcome: "send-lost", changed, code: CODES.writeUnknown });'), /"send-lost" is not an outcome a row can be recorded with/],+ ['a computed value', source.replace(lostSend, "const nextOutcome = ['send', 'lost'].join('-'); record(item.rowId, { outcome: nextOutcome, changed, code: CODES.writeUnknown });"), /"send-lost" is not an outcome a row can be recorded with/],+ ['an outcome the facts do not show', source.replace(lostSend, "record(item.rowId, { outcome: 'acknowledged', changed });"), /"acknowledged" is not what the row's facts show/],+ ]) {+ await assert.rejects(throughWriter(writerFrom(mutated), { patch: lose }), (e) => e instanceof TypeError && said.test(e.message), what);+ }+});++// Every literal (string of either quote, template, regular expression) in `source` that says claim words, outside [from, to): found by the+// plugin's lexer, which blanks exactly the literals and comments, so neither the quote style, the case nor a comment can hide or fake one.+const CLAIM_WORDS = /\baccept(?:s|ed|ing|ance)?\b|\backnowledg(?:e|es|ed|ing|ement|ements|ment|ments)\b|\bsav(?:e|es|ed|ing)\b(?! customizations)|\bunknown outcome\b|\boutcome (?:is )?unknown\b|(?<!not )\bwritten by this build\b/gi;+function claimWordingOutside(source, from = 0, to = 0) {+ const blank = blankLiterals(source);+ const comments = commentRanges(source);+ const found = [];+ for (const m of source.matchAll(CLAIM_WORDS)) {+ const at = m.index;+ if (at >= from && at < to) continue;+ if (comments.some((c) => at >= c.start && at < c.end)) continue;+ // In code, a word stays as it is; in a literal the lexer blanks every character of it.+ if (blank[at] === source[at]) continue;+ const line = source.slice(source.lastIndexOf('\n', at) + 1, source.indexOf('\n', at) === -1 ? source.length : source.indexOf('\n', at)).trim();+ found.push(`${m[0]}: ${line.slice(0, 160)}`);+ }+ return found;+}+// The one vocabulary of the writer: from ROW_OUTCOMES to `named`. Its renderer, remedies and messages are outside it and are scanned.+const vocabularyOf = (run) => [run.indexOf('const ROW_OUTCOMES = '), run.indexOf('const named = ')];+function writerSources() {+ const run = fs.readFileSync(LIB, 'utf8');+ const cli = fs.readFileSync(path.join(__dirname, '..', 'build-model-app.js'), 'utf8');+ const from = cli.indexOf('function printCommandStatePlan(');+ const to = cli.indexOf('const PREVIEW_REASON_WORDS');+ assert.ok(from > 0 && to > from, 'the CLI\'s command-state printing is where this reads it');+ return [+ ['lib/command-state-run.js', run, ...vocabularyOf(run)],+ ['lib/command-state-transport.js', fs.readFileSync(path.join(__dirname, '..', 'lib', 'command-state-transport.js'), 'utf8'), 0, 0],+ ['build-model-app.js (command states)', cli.slice(from, to), 0, 0],+ ];+}++test('no literal of the writer\'s sources makes a claim about a row outside the one vocabulary, in any case or listed inflection', async () => {+ const [[, run, from, to]] = writerSources();+ assert.ok(from > 0 && to > from, 'the vocabulary block is where this reads it');+ assert.ok(!run.slice(from, to).includes('function '), 'the vocabulary holds words, not the renderer');+ assert.ok(run.indexOf('const LATE_MISMATCH_REMEDY = ') < from && run.indexOf('function renderRowHistory(') > to, 'remedy and renderer are scanned');+ for (const [name, source, start, end] of writerSources()) assert.deepStrictEqual(claimWordingOutside(source, start, end), [], name);+ // The CLI's row lines go through the renderer too, never through a row's raw outcome alone.+ const [, , [, cli]] = writerSources();+ const print = cli.slice(cli.indexOf('function printCommandStateResult('), cli.indexOf('function reportCommandStatesOfHalt('));+ assert.match(print, /ROW_MESSAGES\.resultLine\(row\)/);+ assert.doesNotMatch(blankLiterals(print), /row\.outcome/);+ // Each spelling is seen outside the vocabulary: either quote, a template, a capital letter, an inflection.+ const label = 'const rowLabel = (r) => `command state ${r.entity}/${r.location}/${r.rowId}`;';+ assert.ok(run.includes(label));+ const remedy = 'const LATE_MISMATCH_REMEDY = \'';+ // A clause appended to the remedy of the final proof, which a halt that sent nothing says.+ const remedyEnd = 'then run the build again\';';+ assert.ok(run.includes(remedyEnd));+ const acknowledgement = run.replace(remedyEnd, 'then run the build again; Acknowledgement of this build\\\'s flag write is confirmed\';');+ for (const [what, mutated] of [+ ['double quotes', run.replace(label, 'const rowLabel = (r) => "accepted " + `command state ${r.entity}/${r.location}/${r.rowId}`;')],+ ['single quotes', run.replace(remedy, `${remedy}saved; `)],+ ['a capital letter', run.replace(remedy, `${remedy}Saved by this build; `)],+ ['an inflection', run.replace(remedy, `${remedy}the platform accepts it; `)],+ ['an acknowledgement', acknowledgement],+ ['an acknowledged write', run.replace(remedy, `${remedy}the write was acknowledged; `)],+ ['a template', run.replace('throw fail(CODES.notConfirmed, ROW_MESSAGES.postWriteMismatch(', 'throw fail(CODES.notConfirmed, `Unknown outcome ${1}` + ROW_MESSAGES.postWriteMismatch(')],+ ['a renderer clause', run.replace('`a read ${where} found the declared flags`', '`a read ${where} found the declared flags, so this build saved them`')],+ ]) {+ assert.notStrictEqual(mutated, run, what);+ assert.strictEqual(claimWordingOutside(mutated, ...vocabularyOf(mutated)).length, 1, what);+ }+ // A comment saying the words is not a message, and a code name is not a literal.+ assert.deepStrictEqual(claimWordingOutside('// accepted\n/* saved */\nconst accepted = saved;\n'), []);++ // And the same capitalized mutation through a real halt that sent nothing: the writer as shipped claims no write, the mutated one does.+ const halt = async (source) => {+ let patches = 0;+ const counted = () => { patches += 1; return undefined; };+ try { await throughWriter(writerFrom(source), { hidden: true, drift: true, patch: counted }); } catch (error) {+ assert.strictEqual(patches, 0, 'the row already held its flags, so the halt follows no write');+ return error;+ }+ assert.fail('the final proof halts');+ };+ const shipped = await halt(run);+ assert.strictEqual(shipped.code, 'command-state-not-confirmed');+ assert.doesNotMatch(unclaimed(shipped.message), CLAIM, shipped.message);+ const mutated = await halt(run.replace(remedy, `${remedy}Saved by this build; `));+ assert.match(mutated.message, CLAIM, 'the behavioural check sees the capitalized claim too');+ const acknowledged = await halt(acknowledgement);+ assert.strictEqual(acknowledged.code, 'command-state-not-confirmed');+ assert.match(acknowledged.message, /Acknowledgement of this build's flag write is confirmed/);+ assert.match(unclaimed(acknowledged.message), CLAIM, 'the behavioural check sees an acknowledgement in a halt that sent nothing');+});diff --git a/plugins/model-apps/scripts/tests/command-state-publication-build.test.js b/plugins/model-apps/scripts/tests/command-state-publication-build.test.jsnew file mode 100644index 000000000..41c48835e--- /dev/null+++ b/plugins/model-apps/scripts/tests/command-state-publication-build.test.js@@ -0,0 +1,735 @@+'use strict';+// The table publication of a build with commandStates, end to end through the build's own entry (build-model-app.js) and its journal: the+// before-app envelope's plain PublishXml, the managed publisher's PublishXml of a table a managed group routes+// (lib/managed-scope-publisher.js), and the SDK's publication of a reconciled table after the envelope is refused. Three things are pinned here:+// - a refused publication is said by its checked facts only (lib/command-state-contract.js serviceAnswerText), never by the platform's+// text, while a build without commandStates keeps quoting that text as it always did;+// - a table the managed publisher confirmed is reported confirmed even when a later table's publish halts the build, and the table whose+// publish failed is reported `failed`, never as unsent; the halt itself is the one the build always threw;+// - a reconciled table the SDK published after the refused envelope is confirmed by that publication, and one it refused stays `failed`;+// - a table the publish phase published after the refused envelope is confirmed by it, and only by an answer that names the table;+// - every table publication of lib/sdk-build.js goes through its one helper (createTablePublication), which tells the observer and says a+// failure by its checked facts — the SDK's refusal, the fallback's and its settle's, the publish phase's, and a managed publish the+// client failed before dispatch — and a source inventory fails on a table publication added outside it.+// tests/command-state-taint.test.js plants the marker in every position of these answers; this file pins the wording and the outcomes.++const test = require('node:test');+const assert = require('node:assert');+const { T, MD, ROW, HIDE, specFor, harness, buildWithJournal } = require('./helpers/command-state-build-harness.js');+const { commandRow, ORIGIN } = require('./helpers/command-state-org.js');+const { createPublicationBarrier } = require('../lib/publication-barrier.js');+const { openManagedContext } = require('../lib/managed-bindings.js');+const { createManagedTablePublisher } = require('../lib/managed-scope-publisher.js');+const { RETRY } = require('../lib/retry-policy.js');+const { makeTempDir } = require('./helpers/temp-dirs.js');++const MARKER = 'planted-service-message W/"498763"';+const TAINT = /planted-service-message|498763/;+const T2 = 'new_case';+const MD2 = '55555555-5555-4555-8555-555555555555';+const ROW2 = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';+const refused = (status) => ({ status, body: { error: { code: '0x80040220', message: MARKER } } });+const everywhere = (out) => [out.caught ? `${out.caught.code} ${out.caught.message}` : '', out.said, out.logged, out.log, out.status].join('\n');++// A store with no managed group: the build's managed publisher is made (sdk-build.js managedTables) and `routed` tables are published by it.+// In a real workspace a committed group of the table routes it (routeStored); the route is set directly here, as nothing else differs.+function managedRun(barrier, spec, routed) {+ const { store } = openManagedContext({ workspaceDir: makeTempDir('cs-pub-store-'), environment: ORIGIN, appUniqueName: spec.app.uniqueName, solutionUniqueName: spec.solution.uniqueName, barrier });+ for (const table of routed) barrier.route(table, 'a managed group of the table');+ return { publicationBarrier: barrier, bindingGroups: { store } };+}++test('with commandStates, a refused before-app publish is said by its status and Dataverse code, never by the platform\'s text', async () => {+ for (const status of [403, 503]) {+ const h = harness({ publishAnswer: () => refused(status) });+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ const out = await buildWithJournal(h, spec, approvals);+ assert.deepStrictEqual(h.published, [[T]], 'the table is published once, before the app');+ assert.ok(out.said.includes(`could not publish table ${T} before the app (PublishXml answered HTTP ${status}, Dataverse error 0x80040220)`), out.said);+ assert.ok(!TAINT.test(everywhere(out)), 'the platform\'s text is nowhere');+ assert.strictEqual(out.caught && out.caught.code, 'command-state-publish-unconfirmed', 'the build still stops on the unconfirmed table');+ }+ // A publish with no answer at all is said by its system code alone.+ const lost = harness({ publishAnswer: () => { throw Object.assign(new Error(MARKER), { code: 'ECONNRESET' }); } });+ const spec = specFor();+ const out = await buildWithJournal(lost, spec, (await lost.approve(spec)).approvals);+ assert.ok(out.said.includes(`could not publish table ${T} before the app (PublishXml got no usable answer (ECONNRESET))`), out.said);+ assert.ok(!TAINT.test(everywhere(out)));+});++test('without commandStates, a refused before-app publish is quoted as it always was', async () => {+ const h = harness({ publishAnswer: () => refused(403) });+ const out = await buildWithJournal(h, specFor(null), { rows: new Set(), tables: new Set() });+ assert.deepStrictEqual(h.published, [[T]], 'the app\'s navigation table is published before the app');+ assert.ok(out.said.includes(`could not publish table ${T} before the app (PublishXml answered HTTP 403: ${MARKER})`), out.said);+});++// Two declared tables a managed group routes: the first table's publish is answered ok and the second's is refused.+async function twoRouted({ commandStates = true } = {}) {+ const barrier = createPublicationBarrier();+ const h = harness({+ barrier,+ tables: { [T]: { metadataId: MD }, [T2]: { metadataId: MD2 } },+ rows: [commandRow(ROW, T, MD), commandRow(ROW2, T2, MD2)],+ publishAnswer: (tables) => (tables.includes(T2) ? refused(503) : undefined),+ });+ const entities = [+ { schemaName: T, displayName: 'Ticket', primaryAttribute: { schemaName: 'new_subject', displayName: 'Subject' } },+ { schemaName: T2, displayName: 'Case', primaryAttribute: { schemaName: 'new_title', displayName: 'Title' } },+ ];+ const spec = specFor(commandStates ? [HIDE, { ...HIDE, entity: T2, rowId: ROW2 }] : null, { entities });+ const approvals = commandStates ? (await h.approve(spec)).approvals : { rows: new Set(), tables: new Set() };+ const out = await buildWithJournal(h, spec, approvals, managedRun(barrier, spec, [T, T2]));+ return { h, out };+}++test('a managed-routed table published before a later table\'s publish halts is reported confirmed; the failed one is reported failed', async () => {+ const { h, out } = await twoRouted();+ assert.deepStrictEqual(h.published, [[T], [T2]], 'each routed table is sent once, by the managed publisher');+ const halt = out.caught;+ assert.ok(halt, 'the build halts');+ // The halt is the managed publisher's, as before: its code, its retry policy and its words are not the feature's to change.+ assert.strictEqual(halt.code, 'managed-publication-unconfirmed');+ assert.strictEqual(halt.retry, RETRY.NEVER);+ assert.match(halt.message, new RegExp(`the publish of table ${T2}: managed-publication-unconfirmed`));+ assert.deepStrictEqual(halt.commandStates.publication, [+ { entity: T2, outcome: 'unconfirmed', basis: 'existing-before-app-table-envelope', reason: 'failed', code: 'command-state-publish-unconfirmed' },+ { entity: T, outcome: 'confirmed', basis: 'existing-before-app-table-envelope', path: 'managed-before-app' },+ ]);+ assert.deepStrictEqual(halt.commandStatePublicationError.tables, [T2], 'only the table whose publish failed is unconfirmed');+ assert.ok(!halt.commandStatePublicationError.message.includes(T), halt.commandStatePublicationError.message);+ assert.ok(!TAINT.test(everywhere(out)), 'the managed publisher\'s halt does not carry the platform\'s text either');+});++test('the managed flush tells onHalt what it settled before a halt, and the halt it throws is the factory\'s whatever onHalt does', async () => {+ const run = async (onHalt) => {+ const barrier = createPublicationBarrier();+ const { store } = openManagedContext({ workspaceDir: makeTempDir('cs-pub-flush-'), environment: ORIGIN, appUniqueName: 'contoso_Support', solutionUniqueName: 'ContosoSD', barrier });+ const send = barrier.gateRequest(async (req) => (req.body.includes(`<entity>${T2}</entity>`) ? { statusCode: 503, headers: {}, body: '' } : { statusCode: 204, headers: {}, body: '' }));+ const client = {+ get: async () => { throw new Error('no layer is read'); },+ post: async (url, body) => { const res = await send({ method: 'POST', url: `${ORIGIN}/api/data/v9.2${url}`, headers: {}, body: JSON.stringify(body) }); return { status: res.statusCode, body: null }; },+ };+ const made = [];+ const halt = (phase, label, code) => { const e = Object.assign(new Error(`${phase} ${label} ${code}`), { code }); made.push(e); return e; };+ const publisher = createManagedTablePublisher({ store, barrier, client, halt });+ barrier.route(T, 'test');+ barrier.route(T2, 'test');+ const thrown = await publisher.flush([T, T2], { phase: 'app-shell', onHalt }).then(() => null, (e) => e);+ return { thrown, made };+ };+ const told = [];+ const seen = await run((partial) => told.push(partial));+ assert.deepStrictEqual(told, [{ published: [T], withheld: [], failed: [T2] }]);+ assert.strictEqual(seen.thrown, seen.made[0], 'the halt the factory made is thrown');+ const throwing = await run(() => { throw new Error('an observer that throws'); });+ assert.strictEqual(throwing.thrown, throwing.made[0], 'an onHalt that throws does not replace the halt');+ const none = await run(undefined);+ assert.strictEqual(none.thrown, none.made[0], 'without onHalt the halt is thrown as before');+});++// A build that reconciles an existing view of a declared table defers the view's publish onto that table (sdk-build.js publishReconciled);+// the before-app envelope names the table, and when the envelope is refused the SDK publishes the reconciled table instead+// (publishReconciledTables). `sdkRefuses(type, id)` says which of the SDK's publishes it refuses; `batch` gives the SDK the publish of+// several artifacts in one request (publishArtifacts), which publishTargets uses for more than one table and retries a refused one alone.+// `sdkKind(type, id, n)` is the kind of an answer it does not refuse (default `verified`); `shipped` is true only for `verified`, as the SDK+// answers (a `submitted` answer, and the `notApplicable` it gives for an artifact it sent nothing for, have `shipped: false`).+// `scopeOf(type, id)` is the answer's publishScope; by default it names the view's table in an `entity` envelope, as the SDK's answer+// for a view, form or chart does (it sends `<importexportxml><entities><entity>new_ticket</entity></entities></importexportxml>`).+// A refusal is the SDK's own shape: its message and the service's error message both carry the platform's text.+const sdkRefusal = () => Object.assign(new Error(`HTTP 400 from https://contoso.crm.dynamics.com/api/data/v9.2/PublishXml: ${MARKER}`), {+ code: 'CONNECTION_ERROR', statusCode: 400, cause: { error: { code: '0x80040220', message: MARKER } },+});+// A publication that THROWS instead (`sdkThrows`): an error of the same shape thrown, as a provider or a callback can; the real SDK throws+// before any request for an artifact its workspace does not hold (ARTIFACT_NOT_FOUND), which the real-bundle case below runs.+const sdkThrown = () => Object.assign(new Error(MARKER), { code: 'CONNECTION_ERROR', statusCode: 400, cause: { error: { code: '0x80040220', message: MARKER } } });+const entityScope = (type, id) => ({ envelope: 'entity', entityLogicalName: id.includes(T2) ? T2 : T, blastRadiusWarning: 'the table is published' });+function reconciling({ commandStates = true, tables = [T], sdkRefuses = () => false, sdkThrows = () => false, batch = false, sdkKind = () => 'verified', scopeOf = entityScope } = {}) {+ const sdkPublishes = [];+ const answer = (type, id) => {+ sdkPublishes.push(`${type} ${id}`);+ if (sdkThrows(type, id)) throw sdkThrown();+ if (sdkRefuses(type, id, sdkPublishes.length)) return { type, id, shipped: false, publish: { kind: 'failed', error: sdkRefusal() } };+ const kind = sdkKind(type, id, sdkPublishes.length);+ const publishScope = scopeOf(type, id);+ return { type, id, shipped: kind === 'verified', publish: kind === undefined ? {} : { kind }, ...(publishScope ? { publishScope } : {}) };+ };+ const h = harness({+ tables: { [T]: { metadataId: MD }, [T2]: { metadataId: MD2 } },+ rows: [commandRow(ROW, T, MD), commandRow(ROW2, T2, MD2)],+ publishAnswer: () => refused(503),+ adaptSdk: (sdk) => {+ // The view the spec declares on each table already exists, so the build reconciles it: view-new_ticket, view-new_case.+ sdk.findArtifact = async (kind, identity) => (kind === 'view' ? `view-${JSON.stringify(identity).includes(T2) ? T2 : T}` : null);+ sdk.publishArtifact = async (type, id) => answer(type, id);+ if (batch) sdk.publishArtifacts = async (targets) => targets.map(({ type, id }) => answer(type, id));+ },+ });+ const entities = [+ { schemaName: T, displayName: 'Ticket', primaryAttribute: { schemaName: 'new_subject', displayName: 'Subject' } },+ { schemaName: T2, displayName: 'Case', primaryAttribute: { schemaName: 'new_title', displayName: 'Title' } },+ ];+ const views = tables.map((entity) => ({ entity, name: entity === T ? 'Active Tickets' : 'Open Cases', columns: [entity === T ? 'new_subject' : 'new_title'] }));+ const states = tables.map((entity) => (entity === T ? HIDE : { ...HIDE, entity: T2, rowId: ROW2 }));+ const spec = specFor(commandStates ? states : null, { entities, views });+ return { h, spec, sdkPublishes };+}+const run = async ({ h, spec }, commandStates = true) => buildWithJournal(h, spec, commandStates ? (await h.approve(spec)).approvals : { rows: new Set(), tables: new Set() });++test('a reconciled table the SDK published after the refused before-app envelope is confirmed by that publication', async () => {+ const on = reconciling();+ const out = await run(on);+ assert.ifError(out.caught);+ assert.deepStrictEqual(on.h.published, [[T]], 'the envelope named the table once, and was refused');+ assert.ok(on.sdkPublishes.includes(`view view-${T}`), 'the SDK published the reconciled table');+ assert.deepStrictEqual(out.result.commandStates.publication, [{ entity: T, outcome: 'confirmed', basis: 'existing-before-app-table-envelope', path: 'sdk-before-app' }]);+ assert.ok(!TAINT.test(everywhere(out)));+ // Without commandStates the same build sends the same requests and also completes.+ const off = reconciling({ commandStates: false });+ const outOff = await run(off, false);+ assert.ifError(outOff.caught);+ assert.deepStrictEqual([off.h.published, off.sdkPublishes], [on.h.published, on.sdkPublishes]);+});++test('a reconciled table whose SDK publication is refused stays unconfirmed, and the build halts before the app as it always did', async () => {+ const on = reconciling({ sdkRefuses: (type) => type === 'view' });+ const out = await run(on);+ assert.strictEqual(out.caught && out.caught.code, 'reconciled-publish-failed', out.caught && out.caught.message);+ assert.deepStrictEqual(out.caught.commandStates.publication, [{ entity: T, outcome: 'unconfirmed', basis: 'existing-before-app-table-envelope', reason: 'failed', code: 'command-state-publish-unconfirmed' }]);+ assert.deepStrictEqual(out.caught.commandStatePublicationError.tables, [T]);+ // The halt says the refusal by its checked facts, never the service's text, here and in what the build printed and journalled.+ assert.ok(out.caught.message.includes('publish view Active Tickets FAILED before the app was written: PublishXml answered HTTP 400, Dataverse error 0x80040220 — '), out.caught.message);+ assert.ok(!TAINT.test(everywhere(out)), 'the platform\'s text is nowhere');+ // The halt is final, so the build's entry settles the publish it still owes (settleOwedPublishes), which the SDK refuses again: said the same way.+ assert.ok(out.said.includes('the build stopped before its publish phase; publish view Active Tickets FAILED: PublishXml answered HTTP 400, Dataverse error 0x80040220 — '), out.said);+ const off = reconciling({ commandStates: false, sdkRefuses: (type) => type === 'view' });+ const outOff = await run(off, false);+ assert.strictEqual(outOff.caught && outOff.caught.code, 'reconciled-publish-failed');+ assert.ok(outOff.said.includes(`the build stopped before its publish phase; publish view Active Tickets FAILED: HTTP 400 from https://contoso.crm.dynamics.com/api/data/v9.2/PublishXml: ${MARKER} — `), outOff.said);+ // With the feature off the halt quotes the SDK's message, as it always did; the policy, the status and the cause are the same either way.+ assert.ok(outOff.caught.message.includes(`FAILED before the app was written: HTTP 400 from https://contoso.crm.dynamics.com/api/data/v9.2/PublishXml: ${MARKER} — `), outOff.caught.message);+ assert.deepStrictEqual([out.caught.retry, out.caught.statusCode, out.caught.phase], [outOff.caught.retry, outOff.caught.statusCode, outOff.caught.phase]);+ assert.strictEqual(out.caught.message.replace(/: PublishXml answered HTTP 400, Dataverse error 0x80040220 — /, ': X — '), outOff.caught.message.replace(/: HTTP 400 from .*? — /, ': X — '), 'only the refusal\'s words differ');+});++test('of two reconciled tables published in one SDK request, only the one it published is confirmed; one published on its retry is confirmed too', async () => {+ // new_ticket is refused in the batch and again alone; new_case is published in the batch.+ const refusedTwice = reconciling({ tables: [T, T2], batch: true, sdkRefuses: (type, id) => id === `view-${T}` });+ const out = await run(refusedTwice);+ assert.strictEqual(out.caught && out.caught.code, 'reconciled-publish-failed', out.caught && out.caught.message);+ assert.deepStrictEqual(out.caught.commandStates.publication.map((p) => [p.entity, p.outcome, p.path || p.reason]), [[T2, 'confirmed', 'sdk-before-app'], [T, 'unconfirmed', 'failed']]);+ // new_ticket is refused in the batch and published on its retry alone.+ let tries = 0;+ const retried = reconciling({ tables: [T, T2], batch: true, sdkRefuses: (type, id) => id === `view-${T}` && ++tries === 1 });+ const outRetried = await run(retried);+ assert.ifError(outRetried.caught);+ assert.deepStrictEqual(outRetried.result.commandStates.publication.map((p) => [p.entity, p.outcome, p.path]), [[T2, 'confirmed', 'sdk-before-app'], [T, 'confirmed', 'sdk-before-app']]);+});+// An SDK answer proves a publication only by a kind that says the request was sent and answered success (publishAnswerProvesPublication):+// the real SDK answers `notApplicable`, with `shipped: false` and no request sent, for an artifact it has nothing to publish for, so such an+// answer — like `none`, `notRequested`, a kind it does not know, or none — leaves the table unconfirmed and the build ends+// `command-state-publish-unconfirmed`, on each of publishTargets' three paths. With the feature off the same build completes as it always did.+const NO_PROOF = ['notApplicable', 'none', 'notRequested', 'queued', undefined];+const outcomeOf = (out) => (out.caught ? out.caught.commandStates : out.result.commandStates).publication.map((p) => [p.entity, p.outcome, p.path || p.reason]);++test('an SDK publication answered with no request made, or an unknown kind, does not confirm the reconciled table (single publish)', async () => {+ for (const kind of NO_PROOF) {+ const on = reconciling({ sdkKind: (type) => (type === 'view' ? kind : 'verified') });+ const out = await run(on);+ assert.strictEqual(out.caught && out.caught.code, 'command-state-publish-unconfirmed', `${kind}: ${out.caught && out.caught.message}`);+ assert.deepStrictEqual(outcomeOf(out), [[T, 'unconfirmed', 'failed']], String(kind));+ assert.ok(on.sdkPublishes.includes(`view view-${T}`), `${kind}: the SDK was asked to publish the reconciled table`);+ assert.ok(!TAINT.test(everywhere(out)), String(kind));+ const off = reconciling({ commandStates: false, sdkKind: (type) => (type === 'view' ? kind : 'verified') });+ const outOff = await run(off, false);+ assert.ifError(outOff.caught);+ assert.deepStrictEqual([off.h.published, off.sdkPublishes], [on.h.published, on.sdkPublishes], `${kind}: the same requests with the feature off`);+ }+});++test('an SDK batch publication answered with no request made does not confirm that table, on the first pass or on its retry', async () => {+ for (const kind of NO_PROOF) {+ const firstPass = reconciling({ tables: [T, T2], batch: true, sdkKind: (type, id) => (id === `view-${T}` ? kind : 'verified') });+ const out = await run(firstPass);+ assert.strictEqual(out.caught && out.caught.code, 'command-state-publish-unconfirmed', `${kind}: ${out.caught && out.caught.message}`);+ assert.deepStrictEqual(outcomeOf(out), [[T2, 'confirmed', 'sdk-before-app'], [T, 'unconfirmed', 'failed']], `first pass ${kind}`);+ // new_ticket is refused in the batch, and its retry alone is answered with the kind.+ let tries = 0;+ const retry = reconciling({ tables: [T, T2], batch: true, sdkRefuses: (type, id) => id === `view-${T}` && ++tries === 1, sdkKind: (type, id) => (id === `view-${T}` ? kind : 'verified') });+ const outRetry = await run(retry);+ assert.strictEqual(outRetry.caught && outRetry.caught.code, 'command-state-publish-unconfirmed', `${kind}: ${outRetry.caught && outRetry.caught.message}`);+ assert.deepStrictEqual(outcomeOf(outRetry), [[T2, 'confirmed', 'sdk-before-app'], [T, 'unconfirmed', 'failed']], `retry ${kind}`);+ assert.ok(retry.sdkPublishes.filter((p) => p === `view view-${T}`).length >= 2, `${kind}: new_ticket was retried after the refused batch`);+ assert.ok(!TAINT.test(everywhere(out)) && !TAINT.test(everywhere(outRetry)), String(kind));+ }+});++test('an SDK publication answered submitted (shipped false), verified or unverifiable confirms the reconciled table on each path', async () => {+ for (const kind of ['submitted', 'verified', 'unverifiable']) {+ const single = await run(reconciling({ sdkKind: () => kind }));+ assert.ifError(single.caught);+ assert.deepStrictEqual(outcomeOf(single), [[T, 'confirmed', 'sdk-before-app']], `single ${kind}`);+ const batch = await run(reconciling({ tables: [T, T2], batch: true, sdkKind: () => kind }));+ assert.ifError(batch.caught);+ assert.deepStrictEqual(outcomeOf(batch), [[T2, 'confirmed', 'sdk-before-app'], [T, 'confirmed', 'sdk-before-app']], `batch ${kind}`);+ let tries = 0;+ const retry = await run(reconciling({ tables: [T, T2], batch: true, sdkRefuses: (type, id) => id === `view-${T}` && ++tries === 1, sdkKind: () => kind }));+ assert.ifError(retry.caught);+ assert.deepStrictEqual(outcomeOf(retry), [[T2, 'confirmed', 'sdk-before-app'], [T, 'confirmed', 'sdk-before-app']], `retry ${kind}`);+ }+});++// ---- Every table publication of the build is heard, and said by its checked facts (sdk-build.js createTablePublication) ----+// The publish phase (8) publishes, through the SDK, each table the build saved a view, chart or form on. When the envelope before the app was+// refused, that publication is the one that names the table after its latest row write, so the observer hears of it: the table is confirmed by+// `sdk-publish-phase`. Only an answer whose publishScope is the table's own entity envelope, of a kind that proves the request was answered,+// names the table; an answer that names another table, an envelope that names none (a dashboard's, the app's), or none, confirms nothing.+// `scopeOf(type, table)` is the answer's publishScope (default: the table's entity envelope, the app's appmodule one); `kind(type, table)` its+// kind; `refuses(type, table)` answers the SDK's refusal instead; `plain(tables)` answers the envelope before the app.+function publishing({ commandStates = true, tables = [T], batch = false, scopeOf, kind = () => 'verified', refuses = () => false, throws = () => false, plain = () => refused(503), barrier, adaptSdk } = {}) {+ const tableOfId = new Map();+ const sdkPublishes = [];+ const answer = (type, id) => {+ sdkPublishes.push(`${type} ${id}`);+ const table = tableOfId.get(id) || null;+ if (throws(type, table)) throw sdkThrown();+ if (refuses(type, table)) return { type, id, shipped: false, publish: { kind: 'failed', error: sdkRefusal() } };+ const k = kind(type, table);+ const publishScope = scopeOf ? scopeOf(type, table) : table ? entityScope(type, table) : { envelope: 'appmodule', blastRadiusWarning: 'the app is published' };+ return { type, id, shipped: k === 'verified', publish: { kind: k }, ...(publishScope ? { publishScope } : {}) };+ };+ const h = harness({+ barrier,+ tables: { [T]: { metadataId: MD }, [T2]: { metadataId: MD2 } },+ rows: [commandRow(ROW, T, MD), commandRow(ROW2, T2, MD2)],+ publishAnswer: plain,+ adaptSdk: (sdk) => {+ // The views the spec declares do not exist yet, so the build creates them; their ids are the mock's (view-1), so the table each was+ // made for is kept here for the answer to name.+ const create = sdk.createArtifact;+ sdk.createArtifact = (type, def) => {+ const made = create(type, def);+ const table = def && (def.entityLogicalName || def.entity);+ if (table) tableOfId.set(made.id, table);+ return made;+ };+ sdk.publishArtifact = async (type, id) => answer(type, id);+ if (batch) sdk.publishArtifacts = async (targets) => targets.map(({ type, id }) => answer(type, id));+ if (adaptSdk) adaptSdk(sdk);+ },+ });+ const entities = [+ { schemaName: T, displayName: 'Ticket', primaryAttribute: { schemaName: 'new_subject', displayName: 'Subject' } },+ { schemaName: T2, displayName: 'Case', primaryAttribute: { schemaName: 'new_title', displayName: 'Title' } },+ ];+ const views = tables.map((entity) => ({ entity, name: entity === T ? 'Active Tickets' : 'Open Cases', columns: [entity === T ? 'new_subject' : 'new_title'] }));+ const states = tables.map((entity) => (entity === T ? HIDE : { ...HIDE, entity: T2, rowId: ROW2 }));+ const spec = specFor(commandStates ? states : null, { entities, views });+ return { h, spec, sdkPublishes };+}++test('a table the publish phase published after the refused before-app envelope is confirmed by that publication, alone or in one batch', async () => {+ for (const [tables, batch] of [[[T], false], [[T, T2], false], [[T, T2], true]]) {+ for (const kind of ['verified', 'submitted', 'unverifiable']) {+ const on = publishing({ tables, batch, kind: () => kind });+ const out = await run(on);+ const what = `${tables.join('+')} batch=${batch} ${kind}`;+ assert.ifError(out.caught);+ assert.deepStrictEqual(on.h.published.map((names) => [...names].sort()), [[...tables].sort()], `${what}: the envelope named the tables once, and was refused`);+ assert.deepStrictEqual(outcomeOf(out), [...tables].sort().map((t) => [t, 'confirmed', 'sdk-publish-phase']), what);+ assert.ok(!TAINT.test(everywhere(out)), what);+ // Without commandStates the same build makes the same SDK publications and completes, as it always did (its envelope names only the+ // app's navigation table, as 2.23.0's did; the feature adds its declared tables to it).+ const off = publishing({ commandStates: false, tables, batch, kind: () => kind });+ const outOff = await run(off, false);+ assert.ifError(outOff.caught);+ assert.deepStrictEqual(off.sdkPublishes, on.sdkPublishes, what);+ }+ }+});++test('a publish-phase answer that does not name the table, or proves no request, confirms nothing', async () => {+ const cases = {+ 'another table': () => ({ envelope: 'entity', entityLogicalName: T2 }),+ 'a dashboard envelope': () => ({ envelope: 'dashboard', dashboardIds: ['d1'] }),+ 'the app envelope': () => ({ envelope: 'appmodule' }),+ 'an entity envelope with no name': () => ({ envelope: 'entity' }),+ 'no publishScope': () => undefined,+ };+ for (const [what, scopeOf] of Object.entries(cases)) {+ const out = await run(publishing({ scopeOf }));+ assert.strictEqual(out.caught && out.caught.code, 'command-state-publish-unconfirmed', `${what}: ${out.caught && out.caught.message}`);+ assert.deepStrictEqual(outcomeOf(out), [[T, 'unconfirmed', 'failed']], what);+ }+ for (const kind of ['notApplicable', 'none', 'notRequested', 'queued']) {+ const out = await run(publishing({ kind: (type) => (type === 'view' ? kind : 'verified') }));+ assert.strictEqual(out.caught && out.caught.code, 'command-state-publish-unconfirmed', kind);+ assert.deepStrictEqual(outcomeOf(out), [[T, 'unconfirmed', 'failed']], kind);+ }+ // Of two tables in one batch, the answer that names new_case confirms new_case alone, even when it is the answer to new_ticket's view.+ const crossed = await run(publishing({ tables: [T, T2], batch: true, scopeOf: () => ({ envelope: 'entity', entityLogicalName: T2 }) }));+ assert.deepStrictEqual(outcomeOf(crossed), [[T2, 'confirmed', 'sdk-publish-phase'], [T, 'unconfirmed', 'failed']]);+});++test('with commandStates, a publish-phase table publication the SDK refused is said by its checked facts; without, quoted as it always was', async () => {+ const on = publishing({ plain: () => undefined, refuses: (type) => type === 'view' });+ const out = await run(on);+ assert.ok(on.sdkPublishes.some((p) => p.startsWith('view ')), 'the SDK was asked to publish the view');+ assert.match(out.said, /publish view Active Tickets[^\n]*PublishXml answered HTTP 400, Dataverse error 0x80040220/, out.said);+ assert.ok(!TAINT.test(everywhere(out)), 'the platform\'s text is nowhere');+ const off = publishing({ commandStates: false, plain: () => undefined, refuses: (type) => type === 'view' });+ const outOff = await run(off, false);+ assert.ok(outOff.said.includes(MARKER), outOff.said);+ assert.deepStrictEqual([off.h.published, off.sdkPublishes], [on.h.published, on.sdkPublishes], 'the same requests');+ assert.strictEqual(!!out.caught, !!outOff.caught, 'the build ends the same way');+});++test('a managed table publication the client failed before it was dispatched is said by its system code, never the client\'s text', async () => {+ const lose = (sdk) => {+ const post = sdk.dataverse.post;+ sdk.dataverse.post = async (url, body) => {+ if (String(body && body.ParameterXml).includes(`<entity>${T}</entity>`)) throw Object.assign(new Error(`socket closed: ${MARKER}`), { code: 'ECONNRESET' });+ return post(url, body);+ };+ };+ const barrier = createPublicationBarrier();+ const on = publishing({ plain: () => undefined, barrier, adaptSdk: lose });+ const out = await buildWithJournal(on.h, on.spec, (await on.h.approve(on.spec)).approvals, managedRun(barrier, on.spec, [T]));+ assert.strictEqual(out.caught && out.caught.code, 'publish-failed', out.caught && out.caught.message);+ assert.deepStrictEqual(on.h.published, [], 'nothing reached the service');+ assert.ok(out.caught.message.includes(`the publish of table ${T}: publish-failed — PublishXml got no usable answer (ECONNRESET)`), out.caught.message);+ assert.ok(everywhere(out).includes('PublishXml got no usable answer (ECONNRESET)'), everywhere(out));+ assert.ok(!TAINT.test(everywhere(out)), 'the client\'s text is nowhere');+ // Without commandStates the halt and its finding are the ones 2.23.0 made, the client's text among them.+ const offBarrier = createPublicationBarrier();+ const off = publishing({ commandStates: false, plain: () => undefined, barrier: offBarrier, adaptSdk: lose });+ const outOff = await buildWithJournal(off.h, off.spec, { rows: new Set(), tables: new Set() }, managedRun(offBarrier, off.spec, [T]));+ assert.strictEqual(outOff.caught && outOff.caught.code, out.caught.code);+ assert.ok(everywhere(outOff).includes(MARKER), 'the client\'s text is quoted as before');+});++// createTablePublication on its own: what each member tells the observer, with the path its call site names, and that the observer is only+// told — what it does or throws changes no answer and no halt.+test('createTablePublication tells the observer what each publication named, partial results on a managed halt included', async () => {+ const { createTablePublication } = require('../lib/sdk-build.js');+ const heard = [];+ const observer = {+ observePlain: (names, outcome, path) => heard.push(['plain', names, outcome && outcome.ok, path]),+ observeSdk: (names, path) => heard.push(['sdk', names, path]),+ observeManaged: (flushed, path) => heard.push(['managed', flushed, path]),+ };+ const flushes = [];+ const halt = Object.assign(new Error('halt'), { code: 'managed-publication-unconfirmed' });+ const managedTables = {+ flush: async (tables, options) => {+ flushes.push(Object.keys(options).sort());+ if (tables.includes(T2)) { options.onHalt({ published: [T], withheld: [], failed: [T2] }); throw halt; }+ return { published: tables, withheld: [] };+ },+ };+ const answers = {+ 'view v1': { publish: { kind: 'verified' }, publishScope: { envelope: 'entity', entityLogicalName: 'NEW_TICKET' } },+ 'view v2': { publish: { kind: 'verified' }, publishScope: { envelope: 'entity', entityLogicalName: T2 } },+ 'view v3': { publish: { kind: 'notApplicable' }, publishScope: { envelope: 'entity', entityLogicalName: T } },+ 'dashboard d1': { publish: { kind: 'verified' }, publishScope: { envelope: 'dashboard' } },+ // The table's name in an envelope that is not the table's own does not say the table was published.+ 'view v4': { publish: { kind: 'verified' }, publishScope: { envelope: 'dashboard', entityLogicalName: T } },+ };+ const provision = { publishArtifact: async (type, id) => ({ type, id, ...answers[`${type} ${id}`] }) };+ const pub = createTablePublication({ observer, provision, runner: { mapLimit: async (items, n, fn) => Promise.all(items.map(fn)) }, managedTables, warn: () => {} });+ assert.strictEqual(pub.checked, true);+ assert.deepStrictEqual(await pub.managed([T], { phase: 'publish', path: 'p', observed: 'managed-publish-phase' }), { published: [T], withheld: [] });+ assert.strictEqual(await pub.managed([T, T2], { phase: 'publish', path: 'p', observed: 'managed-end-of-build' }).catch((e) => e), halt, 'the halt is the flush\'s');+ for (const id of ['v1', 'v2', 'v3', 'v4']) await pub.one('view', id, T, `view ${id}`, { observed: 'sdk-reconcile' });+ await pub.one('dashboard', 'd1', T, 'dashboard d1', { observed: 'sdk-reconcile' });+ await pub.sdk([['view', 'v1'], ['view', 'v2'], ['dashboard', 'd1'], ['view', 'v4']], null, { tableOf: () => T, observed: 'sdk-publish-phase' });+ assert.deepStrictEqual(heard, [+ ['managed', { published: [T], withheld: [] }, 'managed-publish-phase'],+ ['managed', { published: [T], withheld: [], failed: [T2] }, 'managed-end-of-build'],+ ['sdk', [T], 'sdk-reconcile'],+ ['sdk', [T], 'sdk-publish-phase'],+ ]);+ assert.deepStrictEqual(flushes, [['onHalt', 'path', 'phase', 'sayRefusal'], ['onHalt', 'path', 'phase', 'sayRefusal']], 'with an observer the flush is told what to say');+ // Without an observer nothing is told, and the managed flush is asked exactly as 2.23.0 asked it.+ const quiet = createTablePublication({ provision, runner: { mapLimit: async (items, n, fn) => Promise.all(items.map(fn)) }, managedTables, warn: () => {} });+ heard.length = 0;+ flushes.length = 0;+ assert.strictEqual(quiet.checked, false);+ await quiet.managed([T], { phase: 'publish', path: 'p', observed: 'managed-publish-phase' });+ await quiet.one('view', 'v1', T, 'view v1', { observed: 'sdk-reconcile' });+ assert.deepStrictEqual([heard, flushes], [[], [['path', 'phase']]]);+ // An observer that throws changes nothing.+ const loud = createTablePublication({ observer: { observeSdk: () => { throw new Error('observer'); }, observeManaged: () => { throw new Error('observer'); } }, provision, runner: { mapLimit: async (items, n, fn) => Promise.all(items.map(fn)) }, managedTables, warn: () => {} });+ assert.deepStrictEqual(await loud.one('view', 'v1', T, 'view v1', { observed: 'x' }), { type: 'view', id: 'v1', ...answers['view v1'] });+ assert.strictEqual(await loud.managed([T, T2], { phase: 'publish', path: 'p', observed: 'x' }).catch((e) => e), halt);+});++// A halted build publishes what it still owed (settleOwedPublishes), best-effort: a publish the SDK threw on, or answered refused, is a+// warning. In a build with commandStates (`checked`) the warning says it by its checked facts — the status, the Dataverse code, the error's+// own system code — and never the error's message; without, it quotes the message as 2.23.0 did.+test('a publish owed after a halt that throws or is refused is said by its checked facts with commandStates, and quoted without', async () => {+ const { settleOwedPublishes } = require('../lib/sdk-build.js');+ const answers = {+ v1: () => { throw Object.assign(new Error(`socket closed: ${MARKER}`), { code: 'ECONNRESET' }); },+ v2: () => ({ publish: { kind: 'failed', error: sdkRefusal() } }),+ v3: () => ({ publish: { kind: 'failed', error: Object.assign(new Error(`Transport failure reaching ${ORIGIN}/api/data/v9.2/PublishXml: ${MARKER}`), { code: 'CONNECTION_ERROR', statusCode: 0 }) } }),+ };+ const run = async (checked) => {+ const said = [];+ const provision = { publishArtifact: async (type, id) => ({ type, id, ...answers[id]() }) };+ await settleOwedPublishes(provision, [['view', 'v1', ['view One']], ['view', 'v2', ['view Two']], ['view', 'v3', ['view Three']]], (m) => said.push(m), { checked });+ return said.map((line) => line.replace(/^the build stopped before its publish phase; publish (.*?) FAILED: (.*?) — the change is SAVED.*$/, '$1: $2'));+ };+ assert.deepStrictEqual(await run(true), [+ 'view One: PublishXml got no usable answer (ECONNRESET)',+ 'view Two: PublishXml answered HTTP 400, Dataverse error 0x80040220',+ 'view Three: PublishXml got no usable answer (CONNECTION_ERROR)',+ ]);+ assert.deepStrictEqual(await run(false), [+ `view One: socket closed: ${MARKER}`,+ `view Two: HTTP 400 from https://contoso.crm.dynamics.com/api/data/v9.2/PublishXml: ${MARKER}`,+ `view Three: Transport failure reaching ${ORIGIN}/api/data/v9.2/PublishXml: ${MARKER}`,+ ]);+});++// ---- A table publication that THROWS (sdk-build.js createTablePublication) ----+// The vendored SDK answers a refused or unanswered PublishXml by value, but throws before any request for an artifact its workspace does not+// hold (ARTIFACT_NOT_FOUND), and a provider or a callback can throw too. Two things hold whatever throws, and wherever:+// - a table a request already proved published stays confirmed: the helper hears each target as it settles, so a later target's throw, a+// retry's after the batch, or the single-target pass's after a batch that threw does not erase it; the table whose publication threw+// stays unconfirmed, and the error is the one thrown, unchanged;+// - with commandStates the halt and every line around it say the thrown error by its checked facts; its code, cause, status and retry+// policy are the same as without, where it is quoted as 2.23.0 quoted it.+test('a table the real SDK published stays confirmed when a later target of the same publication throws before its request', async () => {+ const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');+ const { createTablePublication } = require('../lib/sdk-build.js');+ const { createCommandStatePublicationObserver } = require('../lib/command-state-run.js');+ const { mapLimit } = require('../lib/entity-provision.js');+ const requests = [];+ const client = Object.fromEntries(['get', 'post', 'patch', 'put', 'delete'].map((method) => [method, async (url, body) => {+ requests.push({ method, url, body });+ return method === 'get' ? { status: 200, body: { value: [] } } : { status: 204 };+ }]));+ client.apiUrl = (p) => `${ORIGIN}/api/data/v9.2${p}`;+ const sdk = createMakerSdk({ instanceUrl: ORIGIN, httpClient: client, workspaceStorage: createNodeWorkspaceStorage(makeTempDir('cs-pub-real-')) });+ await sdk.initWorkspace();+ // A view of new_ticket the workspace holds, and one of new_case it does not: the SDK publishes the first and refuses the second locally.+ const view = await sdk.createArtifact('view', { name: 'Existing View', entityLogicalName: T, columns: [{ name: 'new_subject' }] });+ const MISSING = '99999999-9999-4999-8999-999999999999';+ for (const batch of [false, true]) {+ const runs = {};+ for (const commandStates of [true, false]) {+ const observer = commandStates ? createCommandStatePublicationObserver() : null;+ if (observer) for (const table of [T, T2]) { observer.register(table); observer.noteRowWrite(table); }+ const thrown = [];+ const provision = { publishArtifact: async (type, id) => sdk.publishArtifact(type, id).catch((e) => { thrown.push(e); throw e; }) };+ if (batch) provision.publishArtifacts = async (targets) => sdk.publishArtifacts(targets);+ const start = requests.length;+ const pub = createTablePublication({ observer, provision, runner: { mapLimit }, concurrency: 1, warn: () => {} });+ const caught = await pub.sdk([['view', view.id], ['view', MISSING]], null, { tableOf: (target) => (target[1] === view.id ? T : T2), observed: 'sdk-publish-phase' }).then(() => null, (e) => e);+ const what = `batch=${batch} commandStates=${commandStates}`;+ assert.strictEqual(caught && caught.code, 'ARTIFACT_NOT_FOUND', what);+ assert.strictEqual(caught, thrown[thrown.length - 1], `${what}: the error is the SDK's own`);+ const sends = requests.slice(start).filter((r) => /PublishXml/.test(r.url));+ assert.strictEqual(sends.length, 1, `${what}: one request, for the view the workspace holds`);+ assert.match(sends[0].body.ParameterXml, new RegExp(`<entity>${T}</entity>`), what);+ runs[commandStates] = sends.map((r) => r.body.ParameterXml);+ if (!observer) continue;+ observer.attachFailure(caught);+ assert.deepStrictEqual(caught.commandStates.publication.map((p) => [p.entity, p.outcome, p.path || p.reason]),+ [[T2, 'unconfirmed', 'halted-before-send'], [T, 'confirmed', 'sdk-publish-phase']], what);+ assert.deepStrictEqual(caught.commandStatePublicationError.tables, [T2], what);+ }+ assert.deepStrictEqual(runs.true, runs.false, `batch=${batch}: the same request with the feature off`);+ }+});++test('a table proven by the batch stays confirmed when another table\'s retry throws; a batch that proves nothing confirms nothing', async () => {+ const { createTablePublication, publishTargets } = require('../lib/sdk-build.js');+ const serial = { mapLimit: async (items, n, fn) => { const out = []; for (const [i, item] of items.entries()) out.push(await fn(item, i)); return out; } };+ const scope = (table) => ({ envelope: 'entity', entityLogicalName: table });+ const tableOf = (target) => (target[1] === 'v1' ? T : T2);+ const publishOf = async (provision) => {+ const heard = [];+ const pub = createTablePublication({ observer: { observeSdk: (names, path) => heard.push([names, path]) }, provision, runner: serial, warn: () => {} });+ const caught = await pub.sdk([['view', 'v1'], ['view', 'v2']], null, { tableOf, observed: 'sdk-publish-phase' }).then(() => null, (e) => e);+ return { heard, caught };+ };+ // v1 (new_ticket) is published in the batch, v2 (new_case) refused there; its retry alone throws.+ const boom = sdkThrown();+ const retried = await publishOf({+ publishArtifacts: async (targets) => targets.map(({ type, id }) => (id === 'v1'+ ? { type, id, publish: { kind: 'verified' }, publishScope: scope(T) }+ : { type, id, publish: { kind: 'failed', error: sdkRefusal() }, publishScope: scope(T2) })),+ publishArtifact: async () => { throw boom; },+ });+ assert.strictEqual(retried.caught, boom, 'the retry\'s error, unchanged');+ assert.deepStrictEqual(retried.heard, [[[T], 'sdk-publish-phase']]);+ // A batch answered for one target of two is no answer: nothing it says is read, and the single-target pass that follows proves nothing+ // before v2 throws.+ const partial = await publishOf({+ publishArtifacts: async () => [{ type: 'view', id: 'v1', publish: { kind: 'verified' }, publishScope: scope(T) }],+ publishArtifact: async (type, id) => { if (id === 'v2') throw boom; return { type, id, publish: { kind: 'notApplicable' }, publishScope: scope(T) }; },+ });+ assert.strictEqual(partial.caught, boom);+ assert.deepStrictEqual(partial.heard, []);+ // A batch that throws, then the single-target pass: v1 proven, then v2 throws.+ const fallback = await publishOf({+ publishArtifacts: async () => { throw new Error('batch preflight'); },+ publishArtifact: async (type, id) => { if (id === 'v2') throw boom; return { type, id, publish: { kind: 'submitted' }, publishScope: scope(T) }; },+ });+ assert.strictEqual(fallback.caught, boom);+ assert.deepStrictEqual(fallback.heard, [[[T], 'sdk-publish-phase']]);+ // The thrown error is the SDK's own: its words stay what they were, for what decides a retry reads them (retry-policy.js judgeFailure).+ assert.strictEqual(boom.message, MARKER);+ // publishTargets tells only an answer that proves a request was sent: none for a no-request kind, whatever envelope it carries.+ const told = [];+ await publishTargets({ publishArtifact: async (type, id) => ({ type, id, publish: { kind: 'notApplicable' }, publishScope: scope(T) }) }, serial, 1,+ [['view', 'v1']], null, () => {}, { onProven: (target) => told.push(target) });+ assert.deepStrictEqual(told, []);+});++test('a reconcile\'s own table publication that throws is said by its checked facts with commandStates, and is the SDK\'s error unchanged', async () => {+ const { createTablePublication } = require('../lib/sdk-build.js');+ const { checkedDisplay } = require('../lib/command-state-contract.js');+ for (const observer of [{ observeSdk: () => {} }, null]) {+ const boom = sdkThrown();+ const pub = createTablePublication({ observer, provision: { publishArtifact: async () => { throw boom; } }, runner: { mapLimit: async () => [] }, warn: () => {} });+ const caught = await pub.one('view', 'v1', T, 'view Open Tickets', { observed: 'sdk-reconcile' }).then(() => null, (e) => e);+ assert.strictEqual(caught, boom);+ assert.strictEqual(caught.message, MARKER);+ assert.deepStrictEqual(checkedDisplay(caught), observer+ ? { text: 'PublishXml answered HTTP 400, Dataverse error 0x80040220', code: 'CONNECTION_ERROR' }+ : { text: MARKER, code: 'CONNECTION_ERROR' });+ }+});++// The halt a thrown publication ends a build with, on and off: everything that decides it is the same; only its words differ.+const haltFacts = (halt) => halt && [halt.code, halt.phase, halt.retry, halt.recoverable, halt.statusCode, halt.cause && halt.cause.code, halt.cause && halt.cause.statusCode];++test('a publish-phase table publication that throws after another table\'s was proven: that one stays confirmed, and the halt is said by its checked facts', async () => {+ for (const batch of [false, true]) {+ const on = publishing({ tables: [T, T2], batch, throws: (type, table) => table === T2 });+ const out = await run(on);+ const what = `batch=${batch}`;+ assert.ok(out.caught, what);+ assert.deepStrictEqual(outcomeOf(out), [[T2, 'unconfirmed', 'failed'], [T, 'confirmed', 'sdk-publish-phase']], what);+ assert.ok(out.caught.message.includes('PublishXml answered HTTP 400, Dataverse error 0x80040220'), `${what}: ${out.caught.message}`);+ assert.ok(!TAINT.test(everywhere(out)), `${what}: the thrown error's text is nowhere`);+ const off = publishing({ commandStates: false, tables: [T, T2], batch, throws: (type, table) => table === T2 });+ const outOff = await run(off, false);+ assert.ok(outOff.caught && outOff.caught.message.includes(MARKER), `${what}: without commandStates the halt quotes it as before`);+ assert.deepStrictEqual(haltFacts(out.caught), haltFacts(outOff.caught), `${what}: the same halt but for its words`);+ assert.deepStrictEqual(off.sdkPublishes, on.sdkPublishes, `${what}: the same publications`);+ }+});++test('a reconciled table\'s SDK publication that throws after another\'s was proven: that one stays confirmed, and every line says the error by its checked facts', async () => {+ for (const batch of [false, true]) {+ const on = reconciling({ tables: [T, T2], batch, sdkThrows: (type, id) => id === `view-${T2}` });+ const out = await run(on);+ const what = `batch=${batch}`;+ assert.ok(out.caught, what);+ assert.deepStrictEqual(outcomeOf(out), [[T2, 'unconfirmed', 'failed'], [T, 'confirmed', 'sdk-before-app']], what);+ assert.ok(!TAINT.test(everywhere(out)), `${what}: the thrown error's text is nowhere`);+ assert.ok(out.caught.message.includes('PublishXml answered HTTP 400, Dataverse error 0x80040220'), `${what}: ${out.caught.message}`);+ const off = reconciling({ commandStates: false, tables: [T, T2], batch, sdkThrows: (type, id) => id === `view-${T2}` });+ const outOff = await run(off, false);+ assert.ok(outOff.caught && outOff.caught.message.includes(MARKER), what);+ assert.deepStrictEqual(haltFacts(out.caught), haltFacts(outOff.caught), `${what}: the same halt but for its words`);+ assert.deepStrictEqual(off.sdkPublishes, on.sdkPublishes, `${what}: the same publications`);+ }+});++// After a final halt the build reads what is still saved and not published on the spec's tables (table-publish.js readSavedNotPublished).+// When that READ fails, a build with commandStates says it by its checked facts, as a read (its status, its Dataverse code, the system code+// of a read with no answer, or the field a row got wrong), never the service's text; without, it is quoted as 2.23.0 quoted it. What the read+// found when it succeeded is said the same way in both.+test('after a halt, a saved-layer read that fails is said by its checked facts with commandStates, and quoted without', async () => {+ const { settleOwedPublishes } = require('../lib/sdk-build.js');+ const row = (fields) => ({ savedqueryid: '77777777-7777-4777-8777-777777777777', name: 'Open Tickets', returnedtypecode: T, componentstate: 1, ...fields });+ const views = (rows) => async (url) => ({ status: 200, body: { value: /savedqueries/.test(url) ? rows : [] } });+ const reads = {+ refused: async () => ({ status: 403, body: { error: { code: '0x80040220', message: MARKER } } }),+ 'refused, code planted': async () => ({ status: 403, body: { error: { code: MARKER, message: 'denied' } } }),+ lost: async () => { throw Object.assign(new Error(`socket closed: ${MARKER}`), { code: 'ECONNRESET' }); },+ 'bad componentstate': views([row({ componentstate: MARKER })]),+ 'no table': views([row({ returnedtypecode: '' })]),+ 'not a list': async () => ({ status: 200, body: { value: MARKER } }),+ };+ const CHECKED = {+ refused: 'the saved views: HTTP 403, Dataverse error 0x80040220; check that the signed-in account can read it, and look the error code up',+ 'refused, code planted': 'the saved views: HTTP 403; check that the signed-in account can read it, and look the error code up',+ lost: 'the saved views: no usable answer (ECONNRESET); check the connection and run it again',+ 'bad componentstate': 'the saved views: the answer holds an unreadable value (componentstate); run it again, and if it persists check the environment\'s answer for this read',+ 'no table': 'the saved views: the answer holds a row that cannot be placed; run it again, and if it persists check the environment\'s answer for this read',+ 'not a list': 'the saved views: the answer is not a list of rows; run it again, and if it persists check the environment\'s answer for this read',+ };+ const settle = async (get, checked) => {+ const said = [];+ await settleOwedPublishes({ dataverse: { apiUrl: (p) => `${ORIGIN}/api/data/v9.2${p}`, get } }, [], (m) => said.push(m), { tables: [T], checked });+ return said;+ };+ const couldNot = /^the build stopped before its publish phase; which forms, views and charts on the spec's tables are saved but not published could not be read \((.*)\)\. Run the build again with --publish, or publish these tables in Power Apps: new_ticket\.$/;+ for (const [what, get] of Object.entries(reads)) {+ const on = await settle(get, true);+ assert.strictEqual(on.length, 1, what);+ assert.strictEqual((couldNot.exec(on[0]) || [])[1], CHECKED[what], `${what}: ${on[0]}`);+ const off = await settle(get, false);+ assert.strictEqual(off.length, 1, what);+ assert.ok(couldNot.test(off[0]), `${what}: ${off[0]}`);+ if (['refused', 'lost', 'bad componentstate'].includes(what)) assert.ok(TAINT.test(off[0]), `${what}: without commandStates the reason is quoted as before: ${off[0]}`);+ }+ // A read is named only by one of its three fixed labels: a label it does not know is left out, whatever it holds.+ const { describeSavedNotPublished } = require('../lib/table-publish.js');+ const odd = describeSavedNotPublished({ ok: false, reason: MARKER, facts: { read: MARKER, problem: 'failed', status: 403 } }, [T], { checked: true });+ assert.strictEqual((couldNot.exec(`the build stopped before its publish phase; ${odd}`) || [])[1], 'HTTP 403; check that the signed-in account can read it, and look the error code up');+ // A read that succeeds lists what it found, the same with the feature on and off.+ const found = views([row({})]);+ assert.deepStrictEqual(await settle(found, true), await settle(found, false));+ assert.match((await settle(found, true))[0], /saved but not published on the spec's tables — new_ticket: view Open Tickets\./);+});++// The inventory: every request in lib/sdk-build.js that can publish a table is made inside createTablePublication or publishTargets (which+// only createTablePublication calls), so a table publication added anywhere else fails here until it goes through the helper. The one+// exception is the app's own publish (appWriters), whose request names the app module and no table. Comment lines are skipped; the file's+// line endings are normalised, since a checkout may give it CRLF.+test('every table publication in sdk-build.js goes through createTablePublication', () => {+ const fs = require('node:fs');+ const path = require('node:path');+ const lines = fs.readFileSync(path.join(__dirname, '..', 'lib', 'sdk-build.js'), 'utf8').replace(/\r\n/g, '\n').split('\n');+ const bodyOf = (header) => {+ const start = lines.findIndex((line) => line.startsWith(header));+ assert.ok(start >= 0, `${header} is in the file`);+ const end = lines.findIndex((line, i) => i > start && line === '}');+ assert.ok(end > start, `${header} has a body`);+ return [start, end];+ };+ const helper = bodyOf('function createTablePublication(');+ const targets = bodyOf('async function publishTargets(');+ const PUBLISHES = [+ /\bpublishTablesXml\(/, /\.publishArtifacts?\(/, /\bmanagedTables\.flush\(/, /\bpublishTargets\(/, /PublishXml['"`]/, /PublishAllXml/,+ /\b(pushArtifacts?|enrichDefaultViews)\([^)]*\bpublish:(?!\s*false\b)/,+ ];+ const ALLOWED = [+ { at: /^return provision\.publishArtifact\('app', appId\);$/, why: 'the app\'s own publish (appWriters): its request names the app module, never a table' },+ ];+ const stray = [];+ lines.forEach((line, i) => {+ const code = line.trim();+ if (code.startsWith('//') || code.startsWith('*') || code.startsWith('/*')) return;+ if (!PUBLISHES.some((re) => re.test(code))) return;+ if ([helper, targets].some(([start, end]) => i > start && i < end) || i === targets[0]) return;+ if (ALLOWED.some((a) => a.at.test(code))) return;+ stray.push(`${i + 1}: ${code}`);+ });+ assert.deepStrictEqual(stray, [], 'a table publication outside createTablePublication');+ // publishTargets is reached only through the helper, and every call site names itself to the observer.+ const calls = lines.map((line, i) => [i, line.trim()]).filter(([, code]) => !code.startsWith('//') && /\btablePublication\.(plain|managed|sdk|one)\(/.test(code));+ assert.ok(calls.length >= 11, `the build's table publications go through the helper (${calls.length})`);+ assert.deepStrictEqual(calls.filter(([, code]) => !/\bobserved: '[a-z-]+'/.test(code)).map(([i, code]) => `${i + 1}: ${code}`), [], 'each names its path');+ const observed = [...new Set(calls.map(([, code]) => /\bobserved: '([a-z-]+)'/.exec(code)[1]))].sort();+ assert.deepStrictEqual(observed, ['managed-app-publication', 'managed-before-app', 'managed-end-of-build', 'managed-publish-phase', 'managed-reconcile', 'managed-views-phase',+ 'plain-before-app', 'sdk-app-publication', 'sdk-before-app', 'sdk-publish-phase', 'sdk-reconcile']);+});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/command-state-publication.test.js b/plugins/model-apps/scripts/tests/command-state-publication.test.jsnew file mode 100644index 000000000..f457d43f5--- /dev/null+++ b/plugins/model-apps/scripts/tests/command-state-publication.test.js@@ -0,0 +1,134 @@+'use strict';+// The command-state publication observer (lib/command-state-run.js createCommandStatePublicationObserver): it only records what the build's+// existing before-app table publication answered, and it is the one thing that lets an apply with command states report success. Only a+// non-empty plain publish answered ok, a managed flush that lists the table as published, or the SDK's publication of a reconciled table+// answered as published confirms a table — and only until the next row write on it.++const test = require('node:test');+const assert = require('node:assert');+const { createCommandStatePublicationObserver, CODES } = require('../lib/command-state-run.js');++const observerWith = (...tables) => {+ const o = createCommandStatePublicationObserver();+ for (const t of tables) o.register(t, []);+ return o;+};+const outcomes = (o) => o.snapshot().map((t) => [t.entity, t.outcome]);++test('only a non-empty plain publish answered ok confirms, and only the tables it named', () => {+ const o = observerWith('new_a', 'new_b');+ o.observePlain([], { ok: true });+ assert.deepStrictEqual(o.unconfirmed(), ['new_a', 'new_b'], 'an empty list answers ok without a request: it confirms nothing');+ o.observePlain(['new_a'], { ok: false, reason: 'HTTP 500' });+ assert.deepStrictEqual(o.unconfirmed(), ['new_a', 'new_b'], 'a refused publish confirms nothing');+ assert.strictEqual(o.snapshot()[0].reason, 'failed');+ o.observePlain(['NEW_A', 'new_other'], { ok: true });+ assert.deepStrictEqual(outcomes(o), [['new_a', 'confirmed'], ['new_b', 'unconfirmed']], 'a name is matched in any case; a table nobody declared is ignored');+ assert.strictEqual(o.snapshot()[0].path, 'plain-before-app');+ assert.strictEqual(o.snapshot()[1].code, CODES.publishUnconfirmed);+});++test('a managed flush confirms only the tables it lists as published; a withheld one stays unconfirmed and says why', () => {+ const o = observerWith('new_a', 'new_b', 'new_c');+ o.observeManaged({ published: ['new_a'], withheld: ['new_b'] });+ o.observeManaged(undefined);+ o.observeManaged({ published: 'new_c' });+ assert.deepStrictEqual(outcomes(o), [['new_a', 'confirmed'], ['new_b', 'unconfirmed'], ['new_c', 'unconfirmed']]);+ assert.strictEqual(o.snapshot()[0].path, 'managed-before-app');+ assert.strictEqual(o.snapshot()[1].reason, 'withheld');+ // A table confirmed earlier is not un-confirmed by a later withheld or failed answer about it.+ o.observeManaged({ withheld: ['new_a'] });+ o.observePlain(['new_a'], { ok: false });+ assert.strictEqual(outcomes(o)[0][1], 'confirmed');+});++test('the SDK\'s publication of reconciled tables confirms only the tables it names, and a later row write needs a new one', () => {+ const o = observerWith('new_a', 'new_b');+ o.observePlain(['new_a', 'new_b'], { ok: false });+ o.observeSdk(undefined);+ o.observeSdk('new_b');+ o.observeSdk(['NEW_A', 'new_other']);+ assert.deepStrictEqual(outcomes(o), [['new_a', 'confirmed'], ['new_b', 'unconfirmed']]);+ assert.strictEqual(o.snapshot()[0].path, 'sdk-before-app');+ assert.strictEqual(o.snapshot()[1].reason, 'failed', 'a table it does not name keeps the reason it had');+ o.noteRowWrite('new_a');+ assert.deepStrictEqual(o.unconfirmed(), ['new_a', 'new_b']);+});++test('a row write after a confirmation needs a new one: an earlier publication cannot pay for a later write', () => {+ const o = observerWith('new_a');+ o.observePlain(['new_a'], { ok: true });+ assert.deepStrictEqual(o.unconfirmed(), []);+ o.noteRowWrite('new_a');+ assert.deepStrictEqual(o.unconfirmed(), ['new_a']);+ o.noteRowWrite('new_not_declared');+ o.observePlain(['new_a'], { ok: true });+ assert.deepStrictEqual(o.unconfirmed(), []);+});++test('declaredTables is every registered table once, in order, for the before-app request to name', () => {+ const o = observerWith('new_b', 'NEW_A', 'new_b');+ assert.deepStrictEqual(o.declaredTables(), ['new_a', 'new_b']);+});++test('a halt carries the rows and the publication, not enumerable, and says which tables are saved but not published', () => {+ const o = observerWith('new_a', 'new_b');+ o.trackRows(() => [{ rowId: 'x', outcome: 'acknowledged' }]);+ o.observePlain(['new_b'], { ok: true });+ const error = new Error('halted');+ o.attachFailure(error);+ assert.deepStrictEqual(error.commandStates.rows, [{ rowId: 'x', outcome: 'acknowledged' }]);+ assert.deepStrictEqual(error.commandStates.publication.map((t) => [t.entity, t.outcome, t.reason]), [['new_a', 'unconfirmed', 'halted-before-send'], ['new_b', 'confirmed', undefined]]);+ assert.deepStrictEqual(error.commandStatePublicationError.tables, ['new_a']);+ assert.strictEqual(error.commandStatePublicationError.code, CODES.publishUnconfirmed);+ assert.deepStrictEqual(Object.keys(error), [], 'nothing reaches a serialized error, the journal or a retry\u2019s reading of it');++ const allConfirmed = observerWith('new_a');+ allConfirmed.observePlain(['new_a'], { ok: true });+ const other = new Error('later halt');+ allConfirmed.attachFailure(other);+ assert.strictEqual(other.commandStatePublicationError, undefined);+ assert.ok(other.commandStates);+});++test('an observation that cannot be made never throws and confirms nothing', () => {+ const o = observerWith('new_a');+ assert.doesNotThrow(() => o.observePlain(null, { ok: true }));+ assert.doesNotThrow(() => o.observePlain(['new_a'], null));+ assert.doesNotThrow(() => o.observeManaged({ get published() { throw new Error('boom'); } }));+ assert.doesNotThrow(() => o.attachFailure(Object.freeze(new Error('frozen'))));+ assert.doesNotThrow(() => o.attachFailure(undefined));+ assert.deepStrictEqual(o.unconfirmed(), ['new_a']);+});++test('the publication message says what each table\'s rows are known to hold, from their facts, never "saved" for a write not read back', () => {+ const wording = (rows) => {+ const o = observerWith('new_a');+ o.trackRows(() => rows.map(([facts, entity = 'new_a'], i) => ({ entity, rowId: `r${i}`, facts })));+ const error = new Error('halted');+ o.attachFailure(error);+ assert.strictEqual(error.commandStatePublicationError.code, CODES.publishUnconfirmed);+ assert.match(error.commandStatePublicationError.message, /required table publication was not confirmed; run the build again with publishing\.$/, 'the code\'s remedy is kept');+ return error.commandStatePublicationError.message.split(' — ')[0];+ };+ const read = (result, phase = 'after-every-row') => ({ attempt: 1, kind: 'read', phase, result, ...(result === 'unreadable' ? { code: 'command-state-row-unreadable' } : { hidden: result === 'matched', disabled: false }) });+ const send = (answer, status) => ({ attempt: 1, kind: 'send', answer, ...(status ? { status } : {}), flags: { hidden: true } });+ const SAVED = [read('differed', 'own-step'), send('acknowledged', 204), read('matched', 'readback')];+ const LOST_MATCHED = [read('differed', 'own-step'), send('lost', 503), read('matched', 'readback')];+ const LOST = [read('differed', 'own-step'), send('lost'), read('differed', 'readback')];+ const HELD = [read('matched', 'preflight'), read('matched', 'own-step')];+ assert.strictEqual(wording([[SAVED]]), 'new_a: saved, not published');+ assert.strictEqual(wording([[LOST_MATCHED]]), 'new_a: held the declared flags after a write with no usable answer (not known to be this build\'s), not published', 'a lost answer whose row was later read holding the flags is not called saved');+ assert.strictEqual(wording([[LOST]]), 'new_a: write outcome unknown, not published');+ assert.strictEqual(wording([[[read('differed', 'own-step'), send('refused', 403)]]]), 'new_a: not written, not published');+ assert.strictEqual(wording([[[]]]), 'new_a: not written, not published', 'a row the attempt never reached');+ assert.strictEqual(wording([[HELD]]), 'new_a: already held the declared flags, not published by this build');+ // A read that found other flags, or could not be judged, after one that found them: said as what that last read did.+ assert.strictEqual(wording([[[...SAVED, read('differed')]]]), 'new_a: held other flags than declared at its last read, not published');+ assert.strictEqual(wording([[[...SAVED, read('unreadable')]]]), 'new_a: could not be read at its last read, not published', 'an unreadable read is never said to have found the flags absent');+ assert.strictEqual(wording([[[...HELD, read('unreadable')]]]), 'new_a: could not be read at its last read, not published');+ assert.strictEqual(wording([[SAVED], [LOST], [[]], [SAVED, 'new_other']]), 'new_a: 3 rows (1 saved, 1 outcome unknown, 1 not written), not published', 'mixed rows are counted, per table');+ assert.strictEqual(wording([]), 'new_a: publication not confirmed', 'no row results: no claim about the rows');+ assert.strictEqual(wording([[SAVED], [LOST_MATCHED], [HELD], [[...HELD, read('unreadable')]]]), 'new_a: 4 rows (1 saved, 1 held after a write with no usable answer, 1 already held, 1 could not be read at its last read), not published');+ assert.strictEqual(wording([[undefined]]), 'new_a: write outcome unknown, not published', 'a row with no facts claims nothing');+});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/command-state-read.test.js b/plugins/model-apps/scripts/tests/command-state-read.test.jsnew file mode 100644index 000000000..9ced4dc87--- /dev/null+++ b/plugins/model-apps/scripts/tests/command-state-read.test.js@@ -0,0 +1,446 @@+'use strict';+// lib/command-state-read.js and lib/command-state-transport.js: the strict reading of a modern command row (every column of its kind, a+// missing column never a null, a null never a false), the app/table context it is judged against, the listing of every row of a table over+// every page, and the read-only transport's allowlist. Driven through the plugin's real raw client (`createAzHttpClient`) over a fake+// Dataverse that answers in the platform's shapes (helpers/command-state-org.js), so the requests counted are the ones that reach the wire.+const test = require('node:test');+const assert = require('node:assert');+const { createAzHttpClient } = require('../lib/sdk-http-client.js');+const { createCommandStateTransport } = require('../lib/command-state-transport.js');+const { resolveCommandStateContext, readCommandStateRow, decodeCommandStateRow, listCommandStateRows, verifyCommandStates } = require('../lib/command-state-read.js');+const { REASONS, codeForReasons, canonicalRowId, ROW_SELECT } = require('../lib/command-state-contract.js');+const { createCommandStateOrg, commandRow, json, ORIGIN, APP_ID, OTHER_APP_ID, SELECT_ALL } = require('./helpers/command-state-org.js');++const API = `${ORIGIN}/api/data/v9.0`;+const TICKET = 'aaaaaaaa-0000-4000-8000-000000000001';+const ORDER = 'aaaaaaaa-0000-4000-8000-000000000002';+const NOTE = 'aaaaaaaa-0000-4000-8000-000000000003';+const TABLES = { contoso_ticket: { metadataId: TICKET }, contoso_order: { metadataId: ORDER }, contoso_note: { metadataId: NOTE, inApp: false } };+const id = (n) => `bbbbbbbb-0000-4000-8000-${String(n).padStart(12, '0')}`;+const ticketRow = (n, extra) => commandRow(id(n), 'contoso_ticket', TICKET, extra);++function readerFor(org) {+ const client = createAzHttpClient(ORIGIN, { getToken: () => 'test-token', request: org.request, sleep: async () => {} });+ return createCommandStateTransport({ client, apiUrl: (path) => `${API}${path}` });+}+const expectTicket = { entity: 'contoso_ticket', metadataId: TICKET, appId: APP_ID, inApp: true, optimisticConcurrency: true };++// --- the decoder ------------------------------------------------------------------------------------------------++test('the columns read are exactly the ones the decoder requires', () => {+ assert.deepStrictEqual([...ROW_SELECT], SELECT_ALL);+});++test('an ordinary top-level, active, unmanaged, table-scoped button is a candidate, read as it is stored', () => {+ const decoded = decodeCommandStateRow(ticketRow(1, { hidden: true }), { ...expectTicket, rowId: id(1), location: 0, scope: 'table', requireVersion: true });+ assert.deepStrictEqual({ eligible: decoded.eligible, reasons: decoded.reasons, details: decoded.details }, { eligible: true, reasons: [], details: [] });+ assert.strictEqual(decoded.row.hidden, true);+ assert.strictEqual(decoded.row.disabled, false);+ assert.strictEqual(decoded.row.scope, 'table');+ assert.strictEqual(decoded.row.bar, 'MainTab');+ assert.strictEqual(decoded.row.version, 'W/"1001"');+});++test('only a table-scoped button is a candidate: an app-scoped one, this app\u2019s own included, is refused for its scope', () => {+ for (const [owner, scope] of [[APP_ID, 'app'], [`{${APP_ID.toUpperCase()}}`, 'app'], [OTHER_APP_ID, 'other-app']]) {+ const decoded = decodeCommandStateRow(ticketRow(1, { _appmoduleid_value: owner }), expectTicket);+ assert.deepStrictEqual([decoded.row.scope, decoded.reasons, decoded.eligible], [scope, ['app-scoped'], false], owner);+ assert.strictEqual(codeForReasons(decoded.reasons), 'command-state-app-scope-unverified', owner);+ }+ assert.strictEqual(codeForReasons(['app-scoped', 'location-mismatch', 'managed']), 'command-state-app-scope-unverified', 'scope is refused before a mismatch');+ assert.strictEqual(codeForReasons(['app-scoped', 'shape-unreadable']), 'command-state-row-unreadable', 'an unreadable row is unreadable first');+ assert.deepStrictEqual(decodeCommandStateRow(ticketRow(1), expectTicket).row.scope, 'table');+ assert.ok(decodeCommandStateRow(ticketRow(1, { _appmoduleid_value: 'app' }), expectTicket).reasons.includes('shape-unreadable'), 'a malformed lookup is unreadable');+});++test('static visibility is a PRESENT null or 0 with every formula column present and empty; anything else is not static', () => {+ // The shape the platform answered for a button a plain commands[] build wrote: visibilitytype null, every formula column null.+ const measured = {+ '@odata.etag': 'W/"5550101"', appactionid: id(1), name: 'n', uniquename: 'u', buttonlabeltext: 'Escalate', context: 1, contextvalue: 'contoso_ticket',+ _contextentity_value: TICKET, _appmoduleid_value: null, location: 0, type: 0, origin: 0, statecode: 0, statuscode: 1, ismanaged: false,+ iscustomizable: { Value: true, CanBeChanged: true, ManagedPropertyLogicalName: 'iscustomizableanddeletable' }, _parentappactionid_value: null,+ hidden: false, isdisabled: false, visibilitytype: null, visibilityformulacomponentlibrary: null, _visibilityformulacomponentlibraryid_value: null,+ visibilityformulacomponentname: null, visibilityformulafunctionname: null, onclickeventtype: 2,+ };+ const decoded = decodeCommandStateRow(measured, { ...expectTicket, rowId: id(1), location: 0, requireVersion: true });+ assert.deepStrictEqual([decoded.eligible, decoded.reasons, decoded.details, decoded.row.visibilityType], [true, [], [], null]);+ const empty = { visibilityformulacomponentlibrary: '', _visibilityformulacomponentlibraryid_value: '', visibilityformulacomponentname: '', visibilityformulafunctionname: '' };+ for (const visibilitytype of [null, 0]) {+ assert.deepStrictEqual(decodeCommandStateRow({ ...measured, visibilitytype }, expectTicket).reasons, [], `${visibilitytype}`);+ assert.deepStrictEqual(decodeCommandStateRow({ ...measured, visibilitytype, ...empty }, expectTicket).reasons, [], `${visibilitytype}, empty formula text`);+ for (const [key, value] of [['visibilityformulacomponentlibrary', 'contoso_lib'], ['_visibilityformulacomponentlibraryid_value', id(8)],+ ['visibilityformulacomponentname', 'Screen1'], ['visibilityformulafunctionname', 'IsVisible']]) {+ assert.deepStrictEqual(decodeCommandStateRow({ ...measured, visibilitytype, [key]: value }, expectTicket).reasons, ['visibility-formula'], `${visibilitytype} with ${key}`);+ const missing = { ...measured, visibilitytype };+ delete missing[key];+ assert.ok(decodeCommandStateRow(missing, expectTicket).reasons.includes('shape-unreadable'), `${visibilitytype} without ${key}`);+ }+ }+ for (const visibilitytype of [1, 2, -1, 3]) {+ assert.deepStrictEqual(decodeCommandStateRow({ ...measured, visibilitytype }, expectTicket).reasons, ['visibility-formula'], `${visibilitytype}`);+ }+ for (const visibilitytype of ['0', '', false, 0.5, {}]) {+ assert.ok(decodeCommandStateRow({ ...measured, visibilitytype }, expectTicket).reasons.includes('shape-unreadable'), JSON.stringify(visibilitytype));+ }+ const missingType = { ...measured };+ delete missingType.visibilitytype;+ const decodedMissing = decodeCommandStateRow(missingType, expectTicket);+ assert.ok(decodedMissing.reasons.includes('shape-unreadable') && decodedMissing.details.includes('visibilitytype is missing'), 'a missing visibilitytype is no null');+});++test('every excluded shape is named by its own reason, and the refusal it stands for', () => {+ const cases = [+ [{ context: 0 }, ['context-not-table'], 'command-state-target-mismatch'],+ [{ contextvalue: 'contoso_order' }, ['context-mismatch'], 'command-state-target-mismatch'],+ [{ _contextentity_value: ORDER }, ['context-mismatch'], 'command-state-target-mismatch'],+ [{ location: 3 }, ['location-unsupported'], 'command-state-target-mismatch'],+ [{ location: 6 }, ['location-unsupported'], 'command-state-target-mismatch'],+ [{ type: 1 }, ['not-standard-button'], 'command-state-target-unsupported'],+ [{ type: 3 }, ['not-standard-button'], 'command-state-target-unsupported'],+ [{ _parentappactionid_value: id(9) }, ['nested'], 'command-state-target-unsupported'],+ [{ origin: 1 }, ['not-default-origin'], 'command-state-target-unsupported'],+ [{ origin: 2 }, ['not-default-origin'], 'command-state-target-unsupported'],+ [{ statecode: 1, statuscode: 2 }, ['inactive'], 'command-state-target-unsupported'],+ [{ statecode: 0, statuscode: 2 }, ['inactive'], 'command-state-target-unsupported'],+ [{ ismanaged: true }, ['managed'], 'command-state-target-unsupported'],+ [{ iscustomizable: { Value: false, CanBeChanged: true } }, ['not-customizable'], 'command-state-target-unsupported'],+ [{ visibilitytype: 1 }, ['visibility-formula'], 'command-state-target-unsupported'],+ [{ visibilitytype: 2 }, ['visibility-formula'], 'command-state-target-unsupported'],+ [{ visibilityformulafunctionname: 'IsVisible' }, ['visibility-formula'], 'command-state-target-unsupported'],+ [{ _visibilityformulacomponentlibraryid_value: id(8) }, ['visibility-formula'], 'command-state-target-unsupported'],+ [{ onclickeventtype: 1 }, ['formula-action'], 'command-state-target-unsupported'],+ [{ '@odata.etag': undefined }, ['version-unavailable'], 'command-state-version-unavailable'],+ [{ '@odata.etag': '"1001"' }, ['version-unavailable'], 'command-state-version-unavailable'],+ [{ '@odata.etag': 'W/"*"' }, ['version-unavailable'], 'command-state-version-unavailable'],+ ];+ for (const [extra, reasons, code] of cases) {+ const row = ticketRow(1, extra);+ for (const [k, v] of Object.entries(extra)) if (v === undefined) delete row[k];+ const decoded = decodeCommandStateRow(row, { ...expectTicket, requireVersion: true });+ assert.deepStrictEqual(decoded.reasons, reasons, JSON.stringify(extra));+ assert.strictEqual(codeForReasons(decoded.reasons), code, JSON.stringify(extra));+ assert.strictEqual(decoded.eligible, false);+ }+ // A JavaScript button and a button with no action are both plain buttons.+ assert.deepStrictEqual(decodeCommandStateRow(ticketRow(1, { onclickeventtype: 0 }), expectTicket).reasons, []);+ // A row asked for by id that answers as another.+ assert.deepStrictEqual(decodeCommandStateRow(ticketRow(2), { ...expectTicket, rowId: id(1) }).reasons, ['id-mismatch']);+ // A declared bar that differs from the stored one.+ assert.deepStrictEqual(decodeCommandStateRow(ticketRow(1, { location: 1 }), { ...expectTicket, location: 0 }).reasons, ['location-mismatch']);+ // Optimistic concurrency off for the table of commands: no row is a candidate, whatever its version.+ assert.deepStrictEqual(decodeCommandStateRow(ticketRow(1), { ...expectTicket, optimisticConcurrency: false }).reasons, ['version-unavailable']);+ // A table that is not one of the app's.+ assert.deepStrictEqual(decodeCommandStateRow(ticketRow(1), { ...expectTicket, inApp: false }).reasons, ['table-not-in-app']);+ assert.strictEqual(codeForReasons(['table-not-in-app', 'managed']), 'command-state-context-unverified');+});++test('a missing column is not a null, a null is not a false, and a number spelled as text is not a number', () => {+ for (const key of ROW_SELECT) {+ const row = ticketRow(1);+ delete row[key];+ const decoded = decodeCommandStateRow(row, expectTicket);+ assert.ok(decoded.reasons.includes('shape-unreadable'), `missing ${key}`);+ assert.ok(decoded.details.includes(`${key} is missing`), `missing ${key}`);+ assert.strictEqual(decoded.eligible, false);+ assert.strictEqual(codeForReasons(decoded.reasons), 'command-state-row-unreadable', key);+ }+ for (const key of ['hidden', 'isdisabled']) {+ for (const value of [null, 0, 'false', 1]) {+ const decoded = decodeCommandStateRow(ticketRow(1, { [key]: value }), expectTicket);+ assert.deepStrictEqual(decoded.reasons, ['flags-unreadable'], `${key}=${JSON.stringify(value)}`);+ assert.strictEqual(decoded.row[key === 'hidden' ? 'hidden' : 'disabled'], null);+ }+ }+ for (const key of ['context', 'location', 'type', 'origin', 'statecode', 'statuscode', 'visibilitytype', 'onclickeventtype']) {+ // A present null is the one shape visibilitytype may have that the others may not (static visibility, tested on its own).+ for (const value of key === 'visibilitytype' ? ['0', 0.5, true] : [null, '0', 0.5, true]) {+ const decoded = decodeCommandStateRow(ticketRow(1, { [key]: value }), expectTicket);+ assert.ok(decoded.reasons.includes('shape-unreadable'), `${key}=${JSON.stringify(value)}`);+ assert.ok(decoded.details.includes(`${key} is not a whole number`), `${key}=${JSON.stringify(value)}`);+ }+ }+ for (const value of [null, 'false', { CanBeChanged: true }, { Value: 'true' }]) {+ assert.ok(decodeCommandStateRow(ticketRow(1, { iscustomizable: value }), expectTicket).reasons.includes('shape-unreadable'), JSON.stringify(value));+ }+ // CanBeChanged is not what a managed property IS.+ assert.deepStrictEqual(decodeCommandStateRow(ticketRow(1, { iscustomizable: { Value: false, CanBeChanged: true } }), expectTicket).reasons, ['not-customizable']);+ assert.ok(decodeCommandStateRow(ticketRow(1, { ismanaged: null }), expectTicket).reasons.includes('shape-unreadable'));+ assert.ok(decodeCommandStateRow(ticketRow(1, { onclickeventtype: 7 }), expectTicket).reasons.includes('shape-unreadable'));+ assert.ok(decodeCommandStateRow(ticketRow(1, { _appmoduleid_value: 'app' }), expectTicket).reasons.includes('shape-unreadable'));+ // An unlabelled button is unlabelled, not named after something else.+ const unlabelled = decodeCommandStateRow(ticketRow(1, { buttonlabeltext: null }), expectTicket);+ assert.deepStrictEqual([unlabelled.row.caption, unlabelled.reasons], [null, []]);+ // The details name columns, never a value the platform sent.+ const odd = decodeCommandStateRow(ticketRow(1, { location: 'secret-value', hidden: 'secret-value' }), expectTicket);+ assert.ok(!JSON.stringify(odd.details).includes('secret-value'));+ assert.throws(() => decodeCommandStateRow(null, expectTicket), { code: 'command-state-row-unreadable' });+});++test('the reasons are a closed vocabulary and every one maps to a refusal', () => {+ for (const reason of REASONS) assert.ok(codeForReasons([reason]), reason);+ assert.strictEqual(codeForReasons([]), null);+ assert.strictEqual(codeForReasons(['managed', 'shape-unreadable']), 'command-state-row-unreadable', 'unreadable outranks unsupported');+});++test('a row id is lower case, hyphenated, without braces and not all zeros', () => {+ assert.strictEqual(canonicalRowId(id(1)), id(1));+ for (const bad of [id(1).toUpperCase(), `{${id(1)}}`, id(1).replace(/-/g, ''), '00000000-0000-0000-0000-000000000000', '', null, 42]) {+ assert.strictEqual(canonicalRowId(bad), null, String(bad));+ }+});++// --- one row by id ------------------------------------------------------------------------------------------------++test('a row is read by its id with every column, and only the platform\u2019s "does not exist" proves it is gone', async () => {+ const org = createCommandStateOrg({ tables: TABLES, rows: [ticketRow(1)] });+ const reader = readerFor(org);+ const found = await readCommandStateRow(reader, id(1));+ assert.strictEqual(found.found, true);+ assert.strictEqual(found.body['@odata.etag'], 'W/"1001"');+ assert.deepStrictEqual(org.requests.map((r) => `${r.method} ${r.path}`), [`GET /appactions(${id(1)})?$select=${SELECT_ALL.join(',')}`]);+ assert.strictEqual(org.requests[0].url.startsWith(`${API}/appactions(`), true);+ assert.deepStrictEqual(await readCommandStateRow(reader, id(2)), { found: false });++ for (const answer of [json(404, { error: { code: '0x80060888', message: 'resource not found' } }), json(404, {}), json(403, { error: { code: '0x80040220' } }),+ json(401, { error: { code: '0x8004a106' } }), json(200, []), { statusCode: 200, headers: {}, body: '<html>sign in</html>' }]) {+ const odd = createCommandStateOrg({ overrides: (req) => (req.path.startsWith('/appactions(') ? answer : undefined) });+ await assert.rejects(readCommandStateRow(readerFor(odd), id(1)), { code: 'command-state-row-unreadable' }, JSON.stringify(answer).slice(0, 80));+ }+ await assert.rejects(readCommandStateRow(reader, id(1).toUpperCase()), { code: 'command-state-row-unreadable' });+ assert.deepStrictEqual(org.writes(), []);+});++// --- the context --------------------------------------------------------------------------------------------------++test('the context is one app by unique name, its current layer, its complete table list and the version switch, in that order', async () => {+ const org = createCommandStateOrg({ tables: TABLES });+ const context = await resolveCommandStateContext(readerFor(org), { appUniqueName: 'contoso_Support', entities: ['Contoso_Ticket', 'contoso_note'] });+ assert.strictEqual(context.appId, APP_ID);+ assert.strictEqual(context.optimisticConcurrency, true);+ assert.deepStrictEqual([...context.tables.values()], [+ { entity: 'contoso_note', metadataId: NOTE, inApp: false },+ { entity: 'contoso_ticket', metadataId: TICKET, inApp: true },+ ]);+ assert.deepStrictEqual(org.requests.map((r) => r.path.replace(/\?.*/, '')), [+ '/appmodules', '/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()', '/appmodulecomponents',+ "/EntityDefinitions(LogicalName='contoso_ticket')", "/EntityDefinitions(LogicalName='contoso_note')", "/EntityDefinitions(LogicalName='appaction')",+ ]);+ assert.deepStrictEqual(org.writes(), []);+ assert.deepStrictEqual(org.unexpected, []);+});++test('no app, two apps, an unreadable layer or component list, an unknown table and no version switch each fail the context', async () => {+ const cases = [+ [{ apps: [] }, 'command-state-context-unverified', /no published app/],+ [{ apps: [{ appmoduleid: APP_ID, uniquename: 'contoso_Support' }, { appmoduleid: OTHER_APP_ID, uniquename: 'contoso_support' }] }, 'command-state-context-unverified', /2 published apps/],+ [{ apps: [{ appmoduleid: 'not-a-guid', uniquename: 'contoso_Support' }] }, 'command-state-context-unverified', /no readable app id/],+ [{ overrides: (req) => (req.path.startsWith('/appmodules/') ? json(200, { value: [] }) : undefined) }, 'command-state-context-unverified', /current layer/],+ [{ overrides: (req) => (req.path.startsWith('/appmodulecomponents') ? json(200, { value: [{ objectid: null, componenttype: 1 }] }) : undefined) }, 'command-state-context-unverified', /its tables: the answer holds a row that cannot be placed \(objectid\); /],+ [{ overrides: (req) => (req.path.startsWith('/appmodulecomponents') ? json(200, {}) : undefined) }, 'command-state-context-unverified', /its tables: the answer is not a list of rows \(value\); /],+ [{ overrides: (req) => (req.path.startsWith('/appmodules?') ? json(403, { error: { code: '0x80040220', message: 'denied' } }) : undefined) }, 'command-state-context-unverified', /HTTP 403/],+ [{ concurrency: 'omit' }, 'command-state-version-unavailable', /row versions/],+ [{ concurrency: null }, 'command-state-version-unavailable', /row versions/],+ [{ overrides: (req) => (req.path.includes("'appaction'") ? json(403, {}) : undefined) }, 'command-state-version-unavailable', /HTTP 403/],+ ];+ for (const [options, code, message] of cases) {+ const org = createCommandStateOrg({ tables: TABLES, ...options });+ await assert.rejects(resolveCommandStateContext(readerFor(org), { appUniqueName: 'contoso_Support', entities: ['contoso_ticket'] }), (err) => {+ assert.strictEqual(err.code, code, String(message));+ assert.match(err.message, message);+ return true;+ }, String(message));+ assert.deepStrictEqual(org.writes(), []);+ }+ const org = createCommandStateOrg({ tables: TABLES });+ await assert.rejects(resolveCommandStateContext(readerFor(org), { appUniqueName: 'contoso_Support', entities: ['contoso_missing'] }), { code: 'command-state-context-unverified' });+ await assert.rejects(resolveCommandStateContext(readerFor(org), { appUniqueName: 'contoso_Support', entities: ['bad name'] }), { code: 'command-state-context-unverified' });+ await assert.rejects(resolveCommandStateContext(readerFor(org), { appUniqueName: ' ' }), { code: 'command-state-context-unverified' });+});++// The design keeps ETags, digests and raw responses out of the feature's halts and journals: every read this module makes, refused with+// the service's own words (here carrying a row version) or cut with no answer, is said by its status, Dataverse code or system code alone.+test('a refused or unanswered read is said by its status and code, never by the service\'s text', async () => {+ const SERVICE = 'planted-service-message W/"498763"';+ const refuse = (prefix) => (req) => (req.path.startsWith(prefix) ? json(403, { error: { code: '0x80040220', message: SERVICE } }) : undefined);+ const cut = (prefix) => (req) => {+ if (req.path.startsWith(prefix)) throw Object.assign(new Error(`socket hang up: ${SERVICE}`), { code: 'ECONNRESET' });+ return undefined;+ };+ const clean = (message, said, what) => {+ assert.match(message, said, what);+ assert.ok(!message.includes('planted-service-message') && !message.includes('498763'), `${what}: ${message}`);+ };+ const context = (overrides) => resolveCommandStateContext(readerFor(createCommandStateOrg({ tables: TABLES, overrides })), { appUniqueName: 'contoso_Support', entities: ['contoso_ticket'] });+ for (const [what, overrides, said] of [+ ['the app', refuse('/appmodules?'), /^app 'contoso_Support': HTTP 403, Dataverse error 0x80040220; /],+ ['its current layer', refuse('/appmodules/'), /its current layer could not be read: HTTP 403, Dataverse error 0x80040220; /],+ ['its current layer, cut', cut('/appmodules/'), /its current layer could not be read: no usable answer \(ECONNRESET\); /],+ ['its tables', refuse('/appmodulecomponents'), /its tables: HTTP 403, Dataverse error 0x80040220; /],+ ['a named table', refuse('/EntityDefinitions(LogicalName=\'contoso_ticket\')'), /the tables contoso_ticket: HTTP 403, Dataverse error 0x80040220; /],+ ]) {+ await assert.rejects(context(overrides), (err) => { assert.strictEqual(err.code, 'command-state-context-unverified', what); clean(err.message, said, what); return true; }, what);+ }+ const org = createCommandStateOrg({ tables: TABLES });+ const resolved = await resolveCommandStateContext(readerFor(org), { appUniqueName: 'contoso_Support', entities: ['contoso_ticket'] });+ const listed = createCommandStateOrg({ tables: TABLES, overrides: refuse('/appactions?') });+ await assert.rejects(listCommandStateRows(readerFor(listed), resolved), (err) => {+ assert.strictEqual(err.code, 'command-state-row-unreadable');+ clean(err.message, /^the modern commands of table 'contoso_ticket': HTTP 403, Dataverse error 0x80040220; /, 'the listing');+ return true;+ });+ const row = createCommandStateOrg({ tables: TABLES, overrides: cut('/appactions(') });+ await assert.rejects(readCommandStateRow(readerFor(row), id(1)), (err) => {+ assert.strictEqual(err.code, 'command-state-row-unreadable');+ clean(err.message, /could not be read: no usable answer \(ECONNRESET\); /, 'a row read with no answer');+ return true;+ });+});++test('with no table named, every table component of the app is resolved by its metadata id, and one that cannot be fails', async () => {+ const org = createCommandStateOrg({ tables: TABLES });+ const context = await resolveCommandStateContext(readerFor(org), { appUniqueName: 'contoso_Support' });+ assert.deepStrictEqual([...context.tables.keys()], ['contoso_order', 'contoso_ticket'], 'the app\u2019s tables only');+ const broken = createCommandStateOrg({ tables: TABLES, overrides: (req) => (req.path.startsWith(`/EntityDefinitions(${ORDER})`) ? json(200, { LogicalName: 'Not A Name', MetadataId: ORDER }) : undefined) });+ await assert.rejects(resolveCommandStateContext(readerFor(broken), { appUniqueName: 'contoso_Support' }), { code: 'command-state-context-unverified' });+});++// --- the listing --------------------------------------------------------------------------------------------------++test('every page of every table is read; excluded rows are listed with their reasons; duplicates carry each other\u2019s id; the order is fixed', async () => {+ const rows = [+ ticketRow(5, { buttonlabeltext: 'Approve', location: 1 }),+ ticketRow(1, { buttonlabeltext: 'Escalate' }),+ ticketRow(2, { buttonlabeltext: 'escalate ', statecode: 1, statuscode: 2 }),+ ticketRow(3, { buttonlabeltext: null }),+ ticketRow(4, { buttonlabeltext: 'Group', type: 3 }),+ ticketRow(6, { buttonlabeltext: 'Header', location: 5 }),+ ticketRow(7, { buttonlabeltext: 'Theirs', _appmoduleid_value: OTHER_APP_ID }),+ ticketRow(8, { buttonlabeltext: 'Migrated', origin: 1 }),+ ticketRow(9, { buttonlabeltext: 'Managed', ismanaged: true }),+ commandRow(id(10), 'contoso_order', ORDER, { buttonlabeltext: 'Ship', location: 2, _appmoduleid_value: APP_ID }),+ ];+ const org = createCommandStateOrg({ tables: TABLES, rows, pageSize: 2 });+ const reader = readerFor(org);+ const context = await resolveCommandStateContext(reader, { appUniqueName: 'contoso_Support' });+ const listed = await listCommandStateRows(reader, context);+ assert.deepStrictEqual(listed.map((x) => [x.table, x.row.location, x.row.caption, x.row.rowId.slice(-2), x.reasons]), [+ ['contoso_order', 2, 'Ship', '10', ['app-scoped']],+ ['contoso_ticket', 0, 'Escalate', '01', []],+ ['contoso_ticket', 0, 'escalate ', '02', ['inactive']],+ ['contoso_ticket', 0, 'Group', '04', ['not-standard-button']],+ ['contoso_ticket', 0, 'Managed', '09', ['managed']],+ ['contoso_ticket', 0, 'Migrated', '08', ['not-default-origin']],+ ['contoso_ticket', 0, 'Theirs', '07', ['app-scoped']],+ ['contoso_ticket', 0, null, '03', []],+ ['contoso_ticket', 1, 'Approve', '05', []],+ ['contoso_ticket', 5, 'Header', '06', ['location-unsupported']],+ ]);+ assert.deepStrictEqual(listed.find((x) => x.row.rowId === id(1)).sameCaption, [id(2)]);+ assert.deepStrictEqual(listed.find((x) => x.row.rowId === id(2)).sameCaption, [id(1)]);+ assert.strictEqual(listed.find((x) => x.row.rowId === id(6)).row.bar, 'unsupported');+ const pages = org.requests.filter((r) => r.path.startsWith('/appactions?'));+ assert.strictEqual(pages.length, 1 + 5, 'one page for the order table, five pages of two for the ticket table');+ assert.ok(pages.every((r) => r.url.startsWith(`${API}/appactions?`)), 'every continuation on the same origin and API root');+ assert.deepStrictEqual(org.writes(), []);+ assert.deepStrictEqual(org.unexpected, []);++ const formOnly = await listCommandStateRows(reader, context, { location: 1 });+ assert.deepStrictEqual(formOnly.map((x) => x.row.rowId), [id(5)]);+});++test('a page that fails, an answer that is no list, a repeated or foreign continuation and a row answered twice fail the listing', async () => {+ const rows = [ticketRow(1), ticketRow(2), ticketRow(3)];+ const second = (answer) => (req) => (req.path.startsWith('/appactions?') && req.path.includes('$skiptoken=2') ? answer(req) : undefined);+ const cases = [+ ['a refused page', second(() => json(403, { error: { code: '0x80040220', message: 'denied' } })), /HTTP 403/],+ ['no value list', second(() => json(200, { rows: [] })), /the answer is not a list of rows \(value\); /],+ ['a sign-in page', second(() => ({ statusCode: 200, headers: { 'content-type': 'text/html' }, body: '<html></html>' })), /the answer is not a list of rows \(value\); /],+ ['a repeated link', (req) => (req.path.startsWith('/appactions?') ? json(200, { value: [], '@odata.nextLink': `${API}/appactions?$select=appactionid&$filter=contextvalue eq 'contoso_ticket'` }) : undefined), /the answer repeated a next-page link; /],+ ['a link to another origin', (req) => (req.path.startsWith('/appactions?') && !req.path.includes('skiptoken') ? json(200, { value: [rows[0]], '@odata.nextLink': `https://fabrikam.crm.dynamics.com/api/data/v9.0/appactions?$skiptoken=2` }) : undefined), /the next-page link pointed outside the expected API and was not followed/],+ ['a link to another resource', (req) => (req.path.startsWith('/appactions?') && !req.path.includes('skiptoken') ? json(200, { value: [rows[0]], '@odata.nextLink': `${API}/systemusers?$skiptoken=2` }) : undefined), /the next-page link pointed outside the expected API and was not followed/],+ ['a malformed link', (req) => (req.path.startsWith('/appactions?') ? json(200, { value: [rows[0]], '@odata.nextLink': 42 }) : undefined), /the answer's next-page link is not a link \(@odata.nextLink\); /],+ ['a row twice', second(() => json(200, { value: [rows[0]] })), /answered twice/],+ ['a row that is no record', second(() => json(200, { value: [null] })), /not a record/],+ ];+ for (const [what, overrides, message] of cases) {+ const org = createCommandStateOrg({ tables: TABLES, rows, overrides });+ const reader = readerFor(org);+ const context = await resolveCommandStateContext(reader, { appUniqueName: 'contoso_Support', entities: ['contoso_ticket'] });+ await assert.rejects(listCommandStateRows(reader, context), (err) => {+ assert.ok(/^command-state-(row-unreadable|transport-unavailable)$/.test(err.code), `${what}: ${err.code}`);+ assert.match(err.message, message, what);+ return true;+ });+ assert.ok(org.requests.every((r) => r.origin === ORIGIN), `${what}: nothing sent elsewhere`);+ assert.ok(org.requests.every((r) => !r.path.startsWith('/systemusers')), `${what}: nothing else read`);+ assert.deepStrictEqual(org.writes(), [], what);+ }+});++// --- the transport ------------------------------------------------------------------------------------------------++test('the transport reads only the feature\u2019s resources, under the SDK\u2019s API root, and writes only one row\u2019s flags', async () => {+ const org = createCommandStateOrg({ tables: TABLES });+ const reader = readerFor(org);+ assert.deepStrictEqual(Object.keys(reader).sort(), ['apiUrl', 'get', 'getAbsolute', 'patchRow']);+ // The one write refuses, before sending, anything but a row id, a row version and a body of only hidden/isdisabled booleans.+ for (const [rowId, ifMatch, body] of [+ ['not-a-guid', 'W/"1"', { hidden: true }], [id(1).toUpperCase(), 'W/"1"', { hidden: true }], [id(1), '*', { hidden: true }], [id(1), undefined, { hidden: true }],+ [id(1), 'W/"1"', {}], [id(1), 'W/"1"', { hidden: 'true' }], [id(1), 'W/"1"', { hidden: true, visibilitytype: 0 }], [id(1), 'W/"1"', { name: 'x' }], [id(1), 'W/"1"', [true]],+ ]) {+ await assert.rejects(reader.patchRow(rowId, ifMatch, body), { code: 'command-state-transport-unavailable' }, JSON.stringify([rowId, ifMatch, body]));+ }+ const readOnly = createCommandStateTransport({ client: { get() {} }, apiUrl: (p) => `${API}${p}` });+ assert.strictEqual(readOnly.patchRow, undefined, 'a client that cannot PATCH gives a transport that cannot write');+ for (const path of ['/systemusers?$select=fullname', '/appactions', `/appactions(${id(1)})`, "/EntityDefinitions(LogicalName='x')?$select=Privileges($select=Name)", '/$batch', 'appactions?$select=name', `${API}/appactions?$select=name`]) {+ await assert.rejects(reader.get(path), { code: 'command-state-transport-unavailable' }, path);+ }+ for (const url of [`https://fabrikam.crm.dynamics.com/api/data/v9.0/appactions?$skiptoken=1`, `${ORIGIN}/api/data/v9.1/appactions?$skiptoken=1`, `${API}/solutions?$skiptoken=1`, '/appactions?$skiptoken=1']) {+ await assert.rejects(reader.getAbsolute(url), { code: 'command-state-transport-unavailable' }, url);+ }+ assert.deepStrictEqual(org.requests, [], 'nothing refused was sent');+ assert.throws(() => createCommandStateTransport({ apiUrl: () => API }), { code: 'command-state-transport-unavailable' });+ assert.throws(() => createCommandStateTransport({ client: { get() {} } }), { code: 'command-state-transport-unavailable' });+ assert.throws(() => createCommandStateTransport({ client: { get() {} }, apiUrl: () => 'not a url' }), { code: 'command-state-transport-unavailable' });+ assert.throws(() => createCommandStateTransport({ client: { get() {} }, apiUrl: () => 'http://contoso.crm.dynamics.com/api/data/v9.0/' }), { code: 'command-state-transport-unavailable' });+});++// --- verification --------------------------------------------------------------------------------------------------++test('verify reads each declared row and checks only the flags it declares, by their spec names; it never writes', async () => {+ const org = createCommandStateOrg({ tables: TABLES, rows: [ticketRow(1, { hidden: true }), ticketRow(2, { isdisabled: true }), ticketRow(3), ticketRow(4, { _appmoduleid_value: APP_ID }), ticketRow(5, { location: 1 })] });+ const spec = {+ app: { uniqueName: 'contoso_Support' },+ commandStates: [+ { entity: 'contoso_ticket', location: 'MainTab', scope: 'table', rowId: id(1), hidden: true },+ { entity: 'contoso_ticket', location: 'MainTab', scope: 'table', rowId: id(2), disabled: true, hidden: false },+ { entity: 'contoso_ticket', location: 'MainTab', scope: 'table', rowId: id(3), disabled: true },+ { entity: 'contoso_ticket', location: 'MainTab', scope: 'table', rowId: id(4), hidden: false },+ { entity: 'contoso_ticket', location: 'MainTab', scope: 'table', rowId: id(5), hidden: false },+ { entity: 'contoso_ticket', location: 'MainTab', scope: 'table', rowId: id(6), hidden: true },+ ],+ };+ const checks = await verifyCommandStates(readerFor(org), spec);+ assert.deepStrictEqual(checks.map((c) => [c.name, c.present]), [+ [`contoso_ticket MainTab row ${id(1)}`, true], [`contoso_ticket MainTab row ${id(2)}`, true], [`contoso_ticket MainTab row ${id(3)}`, false],+ [`contoso_ticket MainTab row ${id(4)}`, false], [`contoso_ticket MainTab row ${id(5)}`, false], [`contoso_ticket MainTab row ${id(6)}`, false],+ ]);+ assert.match(checks[1].detail, /^hidden false, disabled true \(stored flags of the exact row; how the button renders is not checked\)$/);+ assert.match(checks[2].detail, /^disabled is false, declared true/);+ assert.match(checks[3].detail, /not the declared row: app-scoped/);+ assert.match(checks[4].detail, /not the declared row: location-mismatch/);+ assert.match(checks[5].detail, /^the row does not exist/);+ assert.deepStrictEqual(org.writes(), []);+ assert.deepStrictEqual(await verifyCommandStates(readerFor(org), { app: {} }), [], 'no command states: nothing to verify');+});++test('verify fails every entry, never passes or skips one, when the app context or a row cannot be read', async () => {+ const spec = { app: { uniqueName: 'contoso_Missing' }, commandStates: [{ entity: 'contoso_ticket', location: 'MainTab', scope: 'table', rowId: id(1), hidden: true }] };+ const noApp = await verifyCommandStates(readerFor(createCommandStateOrg({ tables: TABLES, rows: [ticketRow(1, { hidden: true })] })), spec);+ assert.deepStrictEqual(noApp.map((c) => c.present), [false]);+ assert.match(noApp[0].detail, /^could not be read: /);+ const odd = createCommandStateOrg({ tables: TABLES, overrides: (req) => (req.path.startsWith('/appactions(') ? json(503, {}) : undefined) });+ const unreadable = await verifyCommandStates(readerFor(odd), { ...spec, app: { uniqueName: 'contoso_Support' } });+ assert.deepStrictEqual(unreadable.map((c) => c.present), [false]);+ assert.match(unreadable[0].detail, /^could not be read: /);+});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/command-state-taint.test.js b/plugins/model-apps/scripts/tests/command-state-taint.test.jsnew file mode 100644index 000000000..f3484f7b6--- /dev/null+++ b/plugins/model-apps/scripts/tests/command-state-taint.test.js@@ -0,0 +1,416 @@+'use strict';+// The class gate for service text in commandStates' messages. The design keeps ETags, digests, handlers and raw responses out of the+// feature's halts and journals, and the service's answers can carry any of them in any string: an error's code or message, a next-page link,+// any field of a row. Each case below plants ONE marker that looks like a row version into ONE string position of ONE answer the feature reads,+// in one phase, and proves the marker reaches none of: the halt, the console lines (warnings and log, the result lines among them), a+// verify detail, the listing's output, build-log.jsonl, build-status.json. Every message about an answer is worded by one formatter+// (lib/command-state-contract.js serviceAnswerText) from checked values only, so the gate holds for any position; a path that copies service+// text again fails the case that reaches it.+//+// The phases:+// preflight a build armed after its dry run: every read from its preflight on is planted+// final a build armed when its table is published, after the row was written and acknowledged: the final completion proof's reads+// write the row PATCH's answer+// listing list-command-states.js, its output as the command line emits it+// verify verifyCommandStates, each declared row's detail+// publish the table publication's answer: the before-app envelope's plain PublishXml and the managed publisher's publish of a table a+// managed group routes (lib/managed-scope-publisher.js), both answered to the build's own Dataverse client and not the org; the+// SDK's refusal of the reconciled table's publication that follows a refused envelope, and of its settle after the final halt+// (`fallback`); the publish phase's SDK publication of a table (`phase8`); and the managed publisher's client failing before the+// request is dispatched (`managed-predispatch`)+//+// The one carve-out is the button's caption (`buttonlabeltext`), which the design shows to a maker: in the listing's `commands[].caption`+// and in the approval display (console only, never journaled). A planted caption may appear there, as exactly what was read, and nowhere else.++const test = require('node:test');+const assert = require('node:assert');+const path = require('node:path');+const { loadCli } = require('./helpers/cli-harness.js');+const realAuth = require('../lib/dataverse-auth.js');+const realHttp = require('../lib/sdk-http-client.js');+const { createCommandStateOrg, commandRow, json, ORIGIN, SELECT_ALL } = require('./helpers/command-state-org.js');+const { T, MD, ROW, specFor, harness, buildWithJournal } = require('./helpers/command-state-build-harness.js');+const { createCommandStateTransport } = require('../lib/command-state-transport.js');+const { verifyCommandStates } = require('../lib/command-state-read.js');+const { createPublicationBarrier } = require('../lib/publication-barrier.js');+const { openManagedContext } = require('../lib/managed-bindings.js');+const { makeTempDir } = require('./helpers/temp-dirs.js');++const MARKER = 'planted-service-message W/"498763"';+const TAINT = /planted-service-message|498763/;+const LISTING = path.resolve(__dirname, '..', 'list-command-states.js');+const apiOf = (req) => /^(.*\/api\/data\/v9\.\d+)/.exec(req.url)[1];+const isGet = (req) => req.method === 'GET';++// Each answer the feature reads, by the request that asks for it.+const RESOURCES = {+ app: { match: (r) => isGet(r) && r.path.startsWith('/appmodules?'), list: true, fields: ['appmoduleid', 'uniquename'] },+ layer: { match: (r) => isGet(r) && r.path.startsWith('/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()'), list: true, fields: ['appmoduleid', 'appmoduleidunique', 'componentstate'] },+ components: { match: (r) => isGet(r) && r.path.startsWith('/appmodulecomponents?'), list: true, fields: ['objectid', 'componenttype'] },+ table: { match: (r) => isGet(r) && r.path.startsWith(`/EntityDefinitions(LogicalName='${T}')`), fields: ['MetadataId', 'EntitySetName'] },+ tableById: { match: (r) => isGet(r) && r.path.startsWith(`/EntityDefinitions(${MD})`), fields: ['LogicalName', 'MetadataId'] },+ concurrency: { match: (r) => isGet(r) && r.path.startsWith("/EntityDefinitions(LogicalName='appaction')"), fields: ['IsOptimisticConcurrencyEnabled'] },+ commands: { match: (r) => isGet(r) && r.path.startsWith('/appactions?'), list: true, fields: [...SELECT_ALL, '@odata.etag', 'iscustomizable.Value'] },+ row: { match: (r) => isGet(r) && r.path.startsWith('/appactions('), fields: [...SELECT_ALL, '@odata.etag', 'iscustomizable.Value'] },+ write: { match: (r) => r.method === 'PATCH' },+};+// Which phase reads which answer.+const PHASES = {+ preflight: ['app', 'layer', 'components', 'table', 'concurrency', 'row'],+ final: ['app', 'layer', 'components', 'table', 'concurrency', 'row'],+ verify: ['app', 'layer', 'components', 'table', 'concurrency', 'row'],+ listing: ['app', 'layer', 'components', 'table', 'tableById', 'concurrency', 'commands'],+ write: ['write'],+};++const refusal = (status, at) => () => ({ status, body: { error: at === 'code' ? { code: MARKER, message: 'denied' } : { code: '0x80040220', message: MARKER } } });+const setField = (record, field) => {+ if (field === 'iscustomizable.Value') return { ...record, iscustomizable: { ...record.iscustomizable, Value: MARKER } };+ return { ...record, [field]: MARKER };+};++// Every position of an answer, as (the answer the org would give, the request) -> the answer planted.+function positionsOf(name) {+ const resource = RESOURCES[name];+ if (name === 'write') {+ const out = {};+ for (const status of [403, 404, 412, 500, 503]) {+ out[`HTTP ${status} error.code`] = refusal(status, 'code');+ out[`HTTP ${status} error.message`] = refusal(status, 'message');+ }+ out['HTTP 404 not-found error.message'] = () => ({ status: 404, body: { error: { code: '0x80040217', message: MARKER } } });+ out['HTTP 200 body'] = () => ({ status: 200, body: { '@odata.etag': MARKER, error: { code: MARKER, message: MARKER } } });+ return out;+ }+ const out = { 'error.code': refusal(403, 'code'), 'error.message': refusal(403, 'message') };+ if (resource.list) {+ out['@odata.nextLink (another origin)'] = (answer) => ({ ...answer, body: { ...answer.body, '@odata.nextLink': `https://example.invalid/${MARKER}` } });+ out['@odata.nextLink (the same API)'] = (answer, req) => ({ ...answer, body: { ...answer.body, '@odata.nextLink': `${apiOf(req)}${req.path.split('?')[0]}?$skiptoken=${MARKER}` } });+ out.value = (answer) => ({ ...answer, body: { ...answer.body, value: MARKER } });+ }+ for (const field of resource.fields) {+ out[field] = resource.list+ ? (answer) => ({ ...answer, body: { ...answer.body, value: answer.body.value.map((row, i) => (i === 0 ? setField(row, field) : row)) } })+ : (answer) => ({ ...answer, body: setField(answer.body, field) });+ }+ if (name === 'row') {+ // A row whose caption changed with its version since the dry run: its approval is stale, and the halts that say so (the approval check,+ // and the re-read just before the write) name the row without its caption.+ const relabelled = (answer) => ({ ...answer, body: { ...setField(answer.body, 'buttonlabeltext'), '@odata.etag': 'W/"2001"' } });+ let reads = 0;+ out['buttonlabeltext, at a new row version'] = relabelled;+ // A build reads the row in its preflight, again in the plan it checks the approvals against, and once more just before the write.+ out['buttonlabeltext, at a new row version, just before the write'] = (answer) => ((reads += 1) < 3 ? answer : relabelled(answer));+ }+ return out;+}++// An org whose answers to one resource are planted while `armed()`; `hits` counts the planted answers served.+function planted(name, plant, armed) {+ const rows = [commandRow(ROW, T, MD)];+ const tables = { [T]: { metadataId: MD } };+ // The answer the org would give, from a twin over the same rows (a GET changes nothing, so the twin always agrees).+ const twin = createCommandStateOrg({ tables, rows });+ const state = { hits: 0 };+ const overrides = async (req) => {+ if (!armed() || !RESOURCES[name].match(req)) return undefined;+ let answer = { status: 0, body: undefined };+ if (isGet(req)) {+ const given = await twin.request({ method: req.method, url: req.url, headers: req.headers });+ answer = { status: given.statusCode, body: JSON.parse(given.body) };+ assert.ok(answer.status >= 200 && answer.status < 300, `the unplanted ${name} answer is a success`);+ }+ const out = plant(answer, req);+ state.hits += 1;+ return json(out.status, out.body);+ };+ return { rows, tables, overrides, state };+}++const isLabel = (name, position) => (name === 'row' || name === 'commands') && position.startsWith('buttonlabeltext');++async function inBuild(phase, name, plant, position) {+ let armed = false;+ const { rows, overrides, state } = planted(name, plant, () => armed);+ const h = harness({ rows, overrides, onPublish: () => { if (phase === 'final') armed = true; } });+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ if (phase !== 'final') armed = true;+ const out = await buildWithJournal(h, spec, approvals);+ if (phase === 'final') assert.strictEqual(h.patches().length, 1, 'the final proof runs after the row write');+ // The approval display is the console's, and the one place a planted caption belongs.+ const display = (out.caught && out.caught.approvalDisplay) || '';+ const unshown = (text) => (isLabel(name, position) && display ? text.split(display).join('') : text);+ return { hits: state.hits, primary: out.caught ? out.caught.message : '', where: whereOf(out, unshown) };+}++// What a build says and leaves, by where.+function whereOf(out, unshown = (text) => text) {+ const states = out.caught && out.caught.commandStates;+ return [+ ['the halt', out.caught ? `${out.caught.code} ${out.caught.message}` : ''],+ ['the warnings', unshown(out.said)],+ ['the console', unshown(out.logged)],+ ['the result', JSON.stringify(states === undefined ? out.result : states) || ''],+ ['build-log.jsonl', out.log],+ ['build-status.json', out.status],+ ];+}++// The publication's answer, planted in each of its positions: the error's code or message at a refusal status, a body that is not JSON, and+// no answer at all (the client throws, as the SDK's does for a failure of the transport).+function publishPositions() {+ const out = {};+ for (const status of [400, 403, 404, 429, 500, 503]) {+ out[`HTTP ${status} error.code`] = () => ({ status, body: { error: { code: MARKER, message: 'denied' } } });+ out[`HTTP ${status} error.message`] = () => ({ status, body: { error: { code: '0x80040220', message: MARKER } } });+ }+ out['HTTP 502 non-JSON body'] = () => ({ status: 502, body: `<html><body>${MARKER}</body></html>` });+ out['no answer'] = () => { throw Object.assign(new Error(MARKER), { code: MARKER }); };+ return out;+}++async function inPublish(route, plant) {+ let hits = 0;+ const barrier = route === 'managed' ? createPublicationBarrier() : undefined;+ const h = harness({ barrier, publishAnswer: async () => { hits += 1; return plant(); } });+ const spec = specFor();+ const { approvals } = await h.approve(spec);+ const engine = {};+ if (barrier) {+ // A committed managed group of the table routes it (managed-scope-publisher.js routeStored); this store holds none, so the route is set here.+ const { store } = openManagedContext({ workspaceDir: makeTempDir('cs-taint-store-'), environment: ORIGIN, appUniqueName: spec.app.uniqueName, solutionUniqueName: spec.solution.uniqueName, barrier });+ barrier.route(T, 'a managed group of the table');+ Object.assign(engine, { publicationBarrier: barrier, bindingGroups: { store } });+ }+ const out = await buildWithJournal(h, spec, approvals, engine);+ return { hits, primary: [out.caught ? out.caught.message : '', out.said].join('\n'), where: whereOf(out) };+}++// The SDK's refusal of a table's publication, planted in each position of the error it answers by value (the vendored SDK's ConnectionError:+// its message quotes the service, its cause carries the service's error), and a transport that got no answer.+function sdkPublishPositions() {+ const refusalWith = (change) => () => {+ const error = Object.assign(new Error('HTTP 503 from https://contoso.crm.dynamics.com/api/data/v9.2/PublishXml: denied'), {+ code: 'CONNECTION_ERROR', statusCode: 503, url: `${ORIGIN}/api/data/v9.2/PublishXml`, cause: { error: { code: '0x80040220', message: 'denied' } },+ });+ change(error);+ return error;+ };+ return {+ 'error.message': refusalWith((e) => { e.message = `HTTP 503 from ${e.url}: ${MARKER}`; }),+ 'error.code': refusalWith((e) => { e.code = MARKER; }),+ 'error.url': refusalWith((e) => { e.url = `${ORIGIN}/${MARKER}`; }),+ 'error.cause.error.message': refusalWith((e) => { e.cause.error.message = MARKER; }),+ 'error.cause.error.code': refusalWith((e) => { e.cause.error.code = MARKER; }),+ 'no answer (transport)': refusalWith((e) => { e.statusCode = 0; e.message = `Transport failure reaching ${ORIGIN}: ${MARKER}`; delete e.cause; }),+ };+}++// The managed publisher's PublishXml failed by the client before it was dispatched, the error's message or its code planted.+function clientFailurePositions() {+ return {+ 'client error.message': () => { throw Object.assign(new Error(MARKER), { code: 'ECONNRESET' }); },+ 'client error.code': () => { throw Object.assign(new Error('socket closed'), { code: MARKER }); },+ };+}++// The read of the saved layer after a final halt (table-publish.js readSavedNotPublished), planted in each position of its answer: the error's+// code or message at a refusal, a body that is not JSON, no answer at all, a row's state and table, and a next-page link. A record's NAME is+// not planted: what the read found is listed by name when it succeeds, with the feature on and off alike (the maker's views and forms).+function savedReadPositions() {+ const row = (fields) => ({ status: 200, body: { value: [{ savedqueryid: '77777777-7777-4777-8777-777777777777', name: 'Open Tickets', returnedtypecode: T, componentstate: 1, ...fields }] } });+ return {+ 'HTTP 403 error.message': () => ({ status: 403, body: { error: { code: '0x80040220', message: MARKER } } }),+ 'HTTP 403 error.code': () => ({ status: 403, body: { error: { code: MARKER, message: 'denied' } } }),+ 'HTTP 502 non-JSON body': () => ({ status: 502, body: `<html><body>${MARKER}</body></html>` }),+ 'no answer error.message': () => { throw Object.assign(new Error(MARKER), { code: 'ECONNRESET' }); },+ 'no answer error.code': () => { throw Object.assign(new Error('socket closed'), { code: MARKER }); },+ componentstate: () => row({ componentstate: MARKER }),+ returnedtypecode: () => row({ returnedtypecode: MARKER }),+ '@odata.nextLink': () => ({ status: 200, body: { value: [], '@odata.nextLink': MARKER } }),+ };+}++// `fallback`: the envelope before the app is refused (its answer is clean) and the SDK's publication of the reconciled table, which follows+// it, answers the planted refusal; the final halt then settles the publish it owes, which is refused the same way. `phase8`: the envelope is+// answered ok and the publish phase's SDK publication of the view the build created answers it. `fallback-thrown` and `phase8-thrown`: the+// same publications THROW the planted error instead of answering it (the SDK throws for a local preflight, a provider or a callback can for+// anything), which the halt is made of. `managed-predispatch`: the table is routed to the managed publisher, whose client fails before the+// request is dispatched. `fallback-read`: the fallback's publication is refused cleanly, the halt is final, and the read of what is still+// saved and not published on the spec's tables that follows it (table-publish.js readSavedNotPublished) answers the plant.+async function inSdkPublish(route, plant) {+ let hits = 0;+ const barrier = route === 'managed-predispatch' ? createPublicationBarrier() : undefined;+ const fallback = route.startsWith('fallback');+ const h = harness({+ barrier,+ publishAnswer: () => (fallback ? { status: 503, body: { error: { code: '0x80040220', message: 'denied' } } } : undefined),+ adaptSdk: (sdk) => {+ if (fallback) sdk.findArtifact = async (kind) => (kind === 'view' ? `view-${T}` : null);+ if (route === 'managed-predispatch') {+ const post = sdk.dataverse.post;+ sdk.dataverse.post = async (url, body) => {+ if (!String(body && body.ParameterXml).includes(`<entity>${T}</entity>`)) return post(url, body);+ hits += 1;+ return plant();+ };+ return;+ }+ if (route === 'fallback-read') {+ let refusedOnce = false;+ sdk.dataverse.get = async (url) => {+ if (!refusedOnce || !/^\/(savedqueries|systemforms|savedqueryvisualizations)\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublishedMultiple\(\)/.test(url)) return { status: 200, body: { value: [] } };+ hits += 1;+ return plant(url);+ };+ sdk.publishArtifact = async (type, id) => {+ if (type !== 'view') return { type, id, shipped: true, publish: { kind: 'verified' } };+ refusedOnce = true;+ const error = Object.assign(new Error(`HTTP 400 from ${ORIGIN}/api/data/v9.2/PublishXml: denied`), { code: 'CONNECTION_ERROR', statusCode: 400, cause: { error: { code: '0x80040220', message: 'denied' } } });+ return { type, id, shipped: false, publish: { kind: 'failed', error } };+ };+ return;+ }+ sdk.publishArtifact = async (type, id) => {+ if (type !== 'view') return { type, id, shipped: true, publish: { kind: 'verified' } };+ hits += 1;+ if (route.endsWith('-thrown')) throw plant();+ return { type, id, shipped: false, publish: { kind: 'failed', error: plant() } };+ };+ },+ });+ const spec = specFor(undefined, { views: [{ entity: T, name: 'Active Tickets', columns: ['new_subject'] }] });+ const { approvals } = await h.approve(spec);+ const engine = {};+ if (barrier) {+ const { store } = openManagedContext({ workspaceDir: makeTempDir('cs-taint-store-'), environment: ORIGIN, appUniqueName: spec.app.uniqueName, solutionUniqueName: spec.solution.uniqueName, barrier });+ barrier.route(T, 'a managed group of the table');+ Object.assign(engine, { publicationBarrier: barrier, bindingGroups: { store } });+ }+ const out = await buildWithJournal(h, spec, approvals, engine);+ return { hits, primary: [out.caught ? out.caught.message : '', out.said].join('\n'), where: whereOf(out) };+}++async function inListing(name, plant, position) {+ const { rows, tables, overrides, state } = planted(name, plant, () => true);+ const org = createCommandStateOrg({ tables, rows, overrides });+ const emitted = [];+ const requires = {+ // emitResult ends the process; here it ends main() instead, as list-command-states.test.js does.+ './lib/dataverse-auth.js': {+ ...realAuth,+ emitResult: (ok, payload) => {+ emitted.push({ ok, payload });+ const exit = new Error(`process.exit(${ok ? 0 : 1})`);+ exit.exitCode = ok ? 0 : 1;+ throw exit;+ },+ },+ './lib/sdk-http-client.js': { ...realHttp, createAzHttpClient: (env) => realHttp.createAzHttpClient(env, { getToken: () => 'test-token', request: org.request, sleep: async () => {} }) },+ };+ // Without --entity the listing resolves the app's tables by metadata id; with it, by logical name.+ const cli = loadCli(LISTING, { requires, argv: ['--env', ORIGIN, '--app', 'contoso_Support', ...(name === 'tableById' ? [] : ['--entity', T])] });+ try {+ await cli.main();+ } catch (error) {+ if (typeof error.exitCode !== 'number') throw error;+ }+ assert.strictEqual(emitted.length, 1, 'one result is emitted');+ const { payload } = emitted[0];+ // A planted caption is listed as exactly what was read, in `caption`, and said nowhere else.+ const commands = Array.isArray(payload.commands) ? payload.commands.map((item) => {+ if (!isLabel(name, position) || item.caption !== MARKER) return item;+ const { caption, ...rest } = item;+ return rest;+ }) : payload.commands;+ return {+ hits: state.hits,+ primary: emitted[0].ok ? '' : JSON.stringify(payload),+ where: [['the listing output', JSON.stringify({ ...payload, ...(commands ? { commands } : {}) })], ['stdout', cli.stdoutText()], ['stderr', cli.stderrText()]],+ };+}++async function inVerify(name, plant) {+ const { rows, tables, overrides, state } = planted(name, plant, () => true);+ const org = createCommandStateOrg({ tables, rows, overrides });+ const reader = createCommandStateTransport({+ client: realHttp.createAzHttpClient(ORIGIN, { getToken: () => 'test-token', request: org.request, sleep: async () => {} }),+ apiUrl: (p) => `${ORIGIN}/api/data/v9.2${p}`,+ });+ const checks = await verifyCommandStates(reader, specFor());+ assert.strictEqual(checks.length, 1);+ return { hits: state.hits, primary: checks[0].present ? '' : checks[0].detail, where: [['the verify detail', JSON.stringify(checks)]] };+}++const cases = [];+for (const [phase, names] of Object.entries(PHASES)) {+ for (const name of names) {+ for (const [position, plant] of Object.entries(positionsOf(name))) cases.push({ phase, name, position, plant });+ }+}+for (const route of ['plain', 'managed']) {+ for (const [position, plant] of Object.entries(publishPositions())) cases.push({ phase: 'publish', name: route, position, plant });+}+for (const route of ['fallback', 'phase8', 'fallback-thrown', 'phase8-thrown']) {+ for (const [position, plant] of Object.entries(sdkPublishPositions())) cases.push({ phase: 'publish', name: route, position, plant });+}+for (const [position, plant] of Object.entries(clientFailurePositions())) cases.push({ phase: 'publish', name: 'managed-predispatch', position, plant });+for (const [position, plant] of Object.entries(savedReadPositions())) cases.push({ phase: 'publish', name: 'fallback-read', position, plant });+const nameOf = (c) => `${c.phase} | ${c.name} | ${c.position}`;++// Known leak cases, each one of the matrix: an app component's objectid and component type and the+// app read's next-page link, at the preflight and in the final proof; the objectid and the link in the listing and in verify; and a refused+// row read, table-row-version read and table read by metadata id, whose message is the service's but whose Dataverse code must be said.+const KNOWN_LEAKS = [+ 'preflight | components | objectid', 'final | components | objectid', 'preflight | components | componenttype', 'final | components | componenttype',+ 'preflight | app | @odata.nextLink (another origin)', 'final | app | @odata.nextLink (another origin)',+ 'listing | components | objectid', 'listing | app | @odata.nextLink (another origin)',+ 'verify | components | objectid', 'verify | app | @odata.nextLink (another origin)',+ 'verify | row | error.message', 'verify | concurrency | error.message', 'listing | tableById | error.message',+ // A refused before-app publish whose message the warning quoted.+ 'publish | plain | HTTP 403 error.message', 'publish | plain | HTTP 503 error.message',+ // The SDK's refusal of the fallback publication, quoted in the warning and copied into the halt and the journal; and the+ // managed publisher's refusal reason when its client failed before the request was dispatched.+ 'publish | fallback | error.message', 'publish | managed-predispatch | client error.message',+ // The read of the saved layer after a final halt, refused with the service's message; and a publication that throws,+ // at the publish phase and at the fallback, whose error's message the halt and the journal copied.+ 'publish | fallback-read | HTTP 403 error.message', 'publish | phase8-thrown | error.message', 'publish | fallback-thrown | error.message',+];+test('the matrix holds every known leak case', () => {+ const names = new Set(cases.map(nameOf));+ assert.deepStrictEqual(KNOWN_LEAKS.filter((n) => !names.has(n)), []);+});++for (const c of cases) {+ test(`no service text: ${nameOf(c)}`, async () => {+ const seen = c.phase === 'listing' ? await inListing(c.name, c.plant, c.position)+ : c.phase === 'verify' ? await inVerify(c.name, c.plant)+ : c.phase === 'publish' ? await (['plain', 'managed'].includes(c.name) ? inPublish(c.name, c.plant) : inSdkPublish(c.name, c.plant))+ : await inBuild(c.phase, c.name, c.plant, c.position);+ assert.ok(seen.hits > 0, 'the planted answer was read');+ if (c.phase === 'preflight' && c.position.startsWith('buttonlabeltext, at')) assert.match(seen.primary, /^command-state-approval-stale\b/, 'the stale-approval halt is reached');+ for (const [where, text] of seen.where) {+ assert.ok(!TAINT.test(text), `${where} holds the planted text: ${text.slice(Math.max(0, text.search(TAINT) - 160), text.search(TAINT) + 60)}`);+ }+ // A refusal whose code is the platform's is still said by its status and that code: the message stays useful without the service's text.+ if (c.phase !== 'publish' && (c.position === 'error.message' || (c.name === 'write' && /^HTTP 40[34] error\.message$/.test(c.position)))) {+ assert.match(seen.primary, /HTTP 40[34], Dataverse error 0x80040220/, 'the status and the Dataverse code are said');+ }+ if (c.phase === 'publish' && c.name === 'plain' && /^HTTP \d+ error\.message$/.test(c.position)) {+ assert.match(seen.primary, /PublishXml answered HTTP \d+, Dataverse error 0x80040220/, 'the refused publish is said by its status and code');+ }+ if (c.phase === 'publish' && ['fallback', 'phase8'].includes(c.name) && c.position === 'error.message') {+ assert.match(seen.primary, /publish view Active Tickets FAILED[^\n]*: PublishXml answered HTTP 503, Dataverse error 0x80040220/, 'the SDK\'s refusal is said by its status and code');+ }+ if (c.phase === 'publish' && ['fallback-thrown', 'phase8-thrown'].includes(c.name) && c.position === 'error.message') {+ assert.match(seen.primary, /PublishXml answered HTTP 503, Dataverse error 0x80040220/, 'the thrown error is said by its status and code');+ }+ if (c.name === 'fallback-read' && c.position === 'HTTP 403 error.message') {+ assert.match(seen.primary, /could not be read \(the saved views: HTTP 403, Dataverse error 0x80040220; check that the signed-in account can read it/, 'the failed read is said as a read, by its status and code');+ }+ if (c.name === 'managed-predispatch' && c.position === 'client error.message') {+ assert.match(seen.primary, /PublishXml got no usable answer \(ECONNRESET\)/, 'the failure is said by its system code');+ }+ });+}diff --git a/plugins/model-apps/scripts/tests/command-state-wiring.test.js b/plugins/model-apps/scripts/tests/command-state-wiring.test.jsnew file mode 100644index 000000000..3cea1f7e4--- /dev/null+++ b/plugins/model-apps/scripts/tests/command-state-wiring.test.js@@ -0,0 +1,191 @@+'use strict';+// How commandStates[] reaches the parts of a build around its writer: the changed-only snapshot diff and classifier (a states-only change is a+// full build, never debt and never a no-op), verification (each entry is checked, and a reader that cannot read command rows fails it), the+// spec document, the --authorize parser and the CLI's refusal of an apply that cannot apply them. A spec without commandStates is unchanged.++const test = require('node:test');+const assert = require('node:assert');+const { diffPhases, PHASE_SLICES, stableStringify } = require('../lib/phase-diff.js');+const { classifyChanges } = require('../lib/classify-changes.js');+const { verifySpec } = require('../lib/verify-spec.js');+const { renderAppSpecDoc } = require('../lib/app-spec-doc.js');+const { buildModelApp, authorizationKeys } = require('../build-model-app.js');+const { commandStateApprovalKey, commandTablePublishApprovalKey } = require('../lib/command-state-contract.js');+const { makeTempDir } = require('./helpers/temp-dirs.js');++const ROW = '11111111-1111-4111-8111-111111111111';+const ROW2 = '22222222-2222-4222-8222-222222222222';+const state = (rowId, extra = {}) => ({ entity: 'new_x', location: 'MainTab', scope: 'table', rowId, hidden: true, ...extra });+const spec = (commandStates) => ({+ schemaVersion: 2,+ minimumPluginVersion: '2.24.0',+ solution: { uniqueName: 'S', publisherPrefix: 'new' },+ app: { name: 'A', uniqueName: 'new_a' },+ appShell: { areas: [{ label: 'M', groups: [{ label: 'G', subAreas: [{ entity: 'new_x' }] }] }] },+ entities: [{ schemaName: 'new_x', primaryAttribute: { schemaName: 'new_name' }, columns: [] }],+ commands: [],+ ...(commandStates ? { commandStates } : {}),+});++test('the commands slice includes command states only when some are declared, in row-id order', () => {+ assert.strictEqual(stableStringify(PHASE_SLICES.commands(spec())), stableStringify(spec().commands), 'no states: the slice is exactly as before');+ assert.strictEqual(stableStringify(PHASE_SLICES.commands(spec([]))), stableStringify(spec().commands));+ const a = spec([state(ROW2), state(ROW)]);+ const b = spec([state(ROW), state(ROW2)]);+ assert.deepStrictEqual(diffPhases(a, b), [], 'their order means nothing');+ assert.ok(diffPhases(spec([state(ROW, { hidden: false })]), spec([state(ROW)])).includes('commands'));+ assert.ok(diffPhases(spec([state(ROW)]), spec()).includes('commands'));+});++test('a command-state-only change is a full build with no debt: added, changed and no longer declared', () => {+ for (const [cur, prior, words] of [+ [spec([state(ROW)]), spec(), 'added'],+ [spec([state(ROW, { disabled: true })]), spec([state(ROW)]), 'changed'],+ [spec(), spec([state(ROW.toUpperCase())]), 'no longer declared'],+ ]) {+ const r = classifyChanges(cur, prior);+ assert.strictEqual(r.verdict, 'full', words);+ assert.deepStrictEqual(r.debt, [], words);+ assert.ok(r.fullReasons.some((x) => x.includes(`row '${ROW}' ${words}`)), `${words}: ${JSON.stringify(r.fullReasons)}`);+ }+ assert.strictEqual(classifyChanges(spec([state(ROW2), state(ROW)]), spec([state(ROW), state(ROW2)])).verdict, 'noop');+});++test('verify checks each declared entry; a reader that cannot read command rows, or a read that fails, fails every one', async () => {+ const base = { findTable: async () => ({ logicalName: 'new_x' }), findColumns: async () => [], queryRecords: async () => [], sitemapXml: async () => '<SiteMap/>' };+ const s = { ...spec([state(ROW), state(ROW2, { disabled: true })]), appShell: { areas: [] } };+ const kind = (r) => r.checks.filter((c) => c.kind === 'command-state').map((c) => [c.name, c.present]);+ const none = await verifySpec(s, base);+ assert.deepStrictEqual(kind(none), [[`new_x MainTab row ${ROW}`, false], [`new_x MainTab row ${ROW2}`, false]]);+ assert.strictEqual(none.ok, false);+ const thrown = await verifySpec(s, { ...base, commandStates: async () => { throw Object.assign(new Error('offline: planted-service-message W/"498763"'), { statusCode: 503 }); } });+ assert.deepStrictEqual(kind(thrown).map((c) => c[1]), [false, false]);+ // A read that throws is said by its status alone, never by the error's own text.+ for (const c of thrown.checks.filter((x) => x.kind === 'command-state')) {+ assert.match(c.detail, /^could not be read: HTTP 503; /, c.detail);+ assert.ok(!c.detail.includes('planted-service-message') && !c.detail.includes('498763'), c.detail);+ }+ const seen = [];+ const read = await verifySpec(s, { ...base, commandStates: async (given) => { seen.push(given); return [{ name: 'one', present: true, detail: 'hidden true' }, { name: 'two', present: false, detail: 'disabled is false, declared true' }]; } });+ assert.deepStrictEqual(kind(read), [['one', true], ['two', false]]);+ assert.strictEqual(seen.length, 1);+ const plain = await verifySpec({ ...spec(), appShell: { areas: [] } }, { ...base, commandStates: async () => { throw new Error('never called'); } });+ assert.deepStrictEqual(kind(plain), [], 'no states: no command-state check');+});++test('a verify of exactly --stage data reports each entry phase-skipped and reads no row; a full or unrestricted verify still checks them', async () => {+ const { STAGES, PHASES } = require('../lib/stages.js');+ const base = { findTable: async () => ({ logicalName: 'new_x' }), findColumns: async () => [], queryRecords: async () => [], sitemapXml: async () => '<SiteMap/>' };+ const s = { ...spec([state(ROW), state(ROW2, { disabled: true })]), appShell: { areas: [] } };+ const kind = (r) => r.checks.filter((c) => c.kind === 'command-state').map((c) => [c.name, c.present]);+ let reads = 0;+ const reader = { ...base, commandStates: async () => { reads += 1; return [{ name: 'one', present: true, detail: 'hidden true' }, { name: 'two', present: true, detail: 'disabled true' }]; } };+ const data = await verifySpec(s, reader, { phases: STAGES.data });+ assert.deepStrictEqual(kind(data), [], 'no command-state check');+ assert.deepStrictEqual(data.phaseSkipped, [`command-state:new_x MainTab row ${ROW}`, `command-state:new_x MainTab row ${ROW2}`]);+ assert.strictEqual(reads, 0, 'and no row read');+ const dataNoReader = await verifySpec(s, base, { phases: STAGES.data });+ assert.deepStrictEqual(kind(dataNoReader), [], 'a reader without command rows does not fail a phase that never ran');+ const full = await verifySpec(s, reader, { phases: PHASES });+ assert.deepStrictEqual(kind(full), [['one', true], ['two', true]]);+ assert.strictEqual(reads, 1);+ const unrestricted = await verifySpec(s, base);+ assert.deepStrictEqual(kind(unrestricted).map((c) => c[1]), [false, false], 'with no phase list a reader that cannot read command rows still fails every entry');+ assert.strictEqual(unrestricted.phaseSkipped, undefined);+});++test('the spec document lists the declared states, with an omitted flag as unchanged, and says nothing when there are none', () => {+ const doc = renderAppSpecDoc(spec([{ entity: 'New_X', location: 'HomeTab', scope: 'table', rowId: ROW, disabled: false }]));+ assert.match(doc, /### Existing command buttons shown or hidden/);+ assert.match(doc, new RegExp(`\\| \`${ROW}\` \\| new_x \\| HomeTab \\| table \\| unchanged \\| no \\|`));+ assert.doesNotMatch(renderAppSpecDoc(spec()), /Existing command buttons/);+});++test('--authorize claims the command-state tokens for the declared rows and tables, and refuses one that names nothing declared', () => {+ const s = spec([state(ROW)]);+ const ids = { origin: 'https://contoso.crm.dynamics.com', appId: ROW2, tableId: ROW2, entity: 'new_x' };+ const row = commandStateApprovalKey({ ...ids, location: 0, rowId: ROW, ifMatch: 'W/"1"', desired: { hidden: true } });+ const table = commandTablePublishApprovalKey(ids);+ const ok = authorizationKeys(['--env', 'https://x', '--authorize', row, `--authorize=${table}`, '--apply'], s);+ assert.strictEqual(ok.error, null);+ assert.deepStrictEqual([[...ok.commandStateRows], [...ok.commandStateTables], [...ok.keys]], [[row], [table], []]);+ const bad = authorizationKeys(['--authorize', row.replace(ROW, ROW2)], s);+ assert.match(bad.error, /names a command row that no commandStates entry declares/);+ const plain = authorizationKeys(['--env', 'https://x'], spec());+ assert.deepStrictEqual([plain.commandStateRows.size, plain.commandStateTables.size, plain.error], [0, 0, null]);+});++test('an apply that cannot apply command states is refused before the build runs; a dry run and a spec without them are not', async () => {+ const runs = [];+ const runBuild = async (s, o) => { runs.push(o); return { ok: true, dryRun: !o.apply, created: {} }; };+ const quiet = { log: () => {}, warn: () => {} };+ for (const [opts, code] of [[{ apply: true }, 'command-state-publish-required'], [{ apply: true, publish: true, changedOnly: { fastApply: true } }, 'command-state-phase-unsupported']]) {+ const r = await buildModelApp(spec([state(ROW)]), { ...opts, workspaceDir: makeTempDir('cs-mode-') }, { runBuild, ...quiet });+ assert.strictEqual(r.ok, false, code);+ assert.ok(r.errors[0].startsWith(`${code}: `), r.errors[0]);+ }+ const keyed = await buildModelApp({ ...spec([state(ROW)]), commands: [{ key: 'go', entity: 'new_x', label: 'Go', library: 'new_go.js', function: 'Ns.go' }], webResources: [{ name: 'new_go.js', type: 'js', content: 'var Ns = {};' }] }, { apply: true, publish: true, workspaceDir: makeTempDir('cs-mode-') }, { runBuild, ...quiet });+ assert.ok(keyed.errors[0].startsWith('command-state-keyed-unsupported: '));+ assert.strictEqual(runs.length, 0, 'nothing ran');+ await buildModelApp(spec([state(ROW)]), { workspaceDir: makeTempDir('cs-mode-') }, { runBuild, ...quiet });+ assert.strictEqual(runs.length, 1, 'a dry run plans them');+ await buildModelApp(spec(), { apply: true, workspaceDir: makeTempDir('cs-mode-') }, { runBuild, ...quiet });+ assert.strictEqual(runs.length, 2, 'no command states: the build runs as before');+});++test('the wrapper refuses an invalid commandStates too, and the engine refuses it when the wrapper only warns', async () => {+ const { runSdkBuild } = require('../lib/sdk-build.js');+ const quiet = { log: () => {}, warn: () => {} };+ for (const [what, value, code] of [['app scope', [state(ROW, { scope: 'app' })], 'command-state-app-scope-unverified'], ['null', null, 'command-state-spec-invalid']]) {+ const bad = { ...spec(), commandStates: value };+ const runs = [];+ const stub = async (s, o) => { runs.push(o); return { ok: true, dryRun: !o.apply, created: {} }; };+ const deployed = await buildModelApp(bad, { apply: true, publish: true, workspaceDir: makeTempDir('cs-spec-') }, { runBuild: stub, ...quiet });+ assert.strictEqual(deployed.ok, false, what);+ assert.ok(deployed.errors.some((e) => e.startsWith(`${code}: `)), `${what}: ${deployed.errors.join(' | ')}`);+ assert.strictEqual(runs.length, 0, `${what}: nothing ran`);+ // A structural profile leaves these findings as warnings, so the spec reaches the engine, which must refuse it before any request.+ let outcome;+ try {+ outcome = await buildModelApp(bad, { profile: 'structural', workspaceDir: makeTempDir('cs-spec-') }, { runBuild: (s, o) => runSdkBuild(s, o), ...quiet });+ } catch (e) {+ outcome = { thrown: e };+ }+ const said = outcome.thrown ? `${outcome.thrown.code}: ${outcome.thrown.message}` : (outcome.errors || []).join(' | ');+ assert.ok(outcome.thrown ? outcome.thrown.code === code : outcome.ok === false && said.includes(code), `${what} (structural): ${said}`);+ }+});++test('the build\'s inline verify reads command rows with the client makeSdk made, as standalone verify does', async () => {+ const fs = require('node:fs');+ const path = require('node:path');+ const { inlineVerifyReader } = require('../build-model-app.js');+ const { createCommandStateOrg, commandRow, ORIGIN } = require('./helpers/command-state-org.js');+ const { createAzHttpClient } = require('../lib/sdk-http-client.js');+ const { createMakerSdk, createNodeWorkspaceStorage } = require('../lib/maker-sdk.js');+ const { commandStateSendOnce } = require('../lib/command-state-transport.js');+ const T = 'new_ticket';+ const MD = '44444444-4444-4444-8444-444444444444';+ const org = createCommandStateOrg({ tables: { [T]: { metadataId: MD } }, rows: [commandRow(ROW, T, MD, { hidden: true })] });+ const client = createAzHttpClient(ORIGIN, { getToken: () => 'offline-token', request: org.request, sleep: async () => {}, sendOnce: commandStateSendOnce });+ const provisionSdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(makeTempDir('cs-inline-')), instanceUrl: ORIGIN, httpClient: client });+ await provisionSdk.initWorkspace();+ const declared = {+ ...spec([{ entity: T, location: 'MainTab', scope: 'table', rowId: ROW, hidden: true }]),+ app: { name: 'Support', uniqueName: 'contoso_Support' },+ entities: [{ schemaName: T, primaryAttribute: { schemaName: 'new_name' }, columns: [] }],+ };+ // The shape makeSdk returns: the reader is given all of it, so nothing it carries can be left out at the call site.+ const reader = inlineVerifyReader({ sdk: provisionSdk, provisionSdk, isolatedReader: null, commandStateClient: client }, declared, { workspaceDir: makeTempDir('cs-inline-') });+ assert.strictEqual(typeof reader.commandStates, 'function', 'the inline reader can read command rows');+ const only = { ...declared, entities: [], app: {}, appShell: { areas: [] } };+ const r = await verifySpec(only, { sitemapXml: async () => '<SiteMap/>', commandStates: () => reader.commandStates(declared) });+ const checks = r.checks.filter((c) => c.kind === 'command-state');+ assert.strictEqual(checks.length, 1);+ assert.strictEqual(checks[0].present, true, JSON.stringify(checks[0]));+ // The build's verify hands the reader the whole makeSdk result, not a list of its fields, and builds no reader any other way.+ const source = fs.readFileSync(path.join(__dirname, '..', 'build-model-app.js'), 'utf8');+ assert.match(source, /const made = await makeSdk\(/);+ assert.match(source, /verifySpec\(s, inlineVerifyReader\(made, s, /);+ assert.strictEqual(source.split('readerFor(').length - 1, 1, 'readerFor is called only inside inlineVerifyReader');+});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/configuration-protected.test.js b/plugins/model-apps/scripts/tests/configuration-protected.test.jsindex e7f5fbd33..ec3b2ff11 100644--- a/plugins/model-apps/scripts/tests/configuration-protected.test.js+++ b/plugins/model-apps/scripts/tests/configuration-protected.test.js@@ -1227,4 +1227,148 @@ test('verify under the opt-in never falls back to a name: no binding store, no bpending.groups = pending.groups.filter((g) => g.family !== 'customApi');pending.pending.push({ family: 'customApi', key: 'contoso_calc', code: 'managed-settlement-pending' });assert.equal(definitions(await read.configuration(configSpec(), undefined, pending))['customApi contoso_Calc'], 'managed-settlement-pending');+});++// ---------------------------------------------------------------------------------------------+// Verify pairs a protected rule's conditions at the ids its binding holds, as the build's plan does: criteria swapped between two+// bound condition rows is a change the build refuses (configuration-edit-unsupported), so verify must fail it too.++const TWO_CONDITIONS = [{ key: 'e', column: 'emailaddress1', match: 'exact' }, { key: 'l', column: 'lastname', match: 'exact' }];+const twoRules = () => configSpec(rule({ conditions: TWO_CONDITIONS }));+const conditionRow = (h, column) => h.org.rows('duplicateruleconditions').find((r) => r.baseattributename === column);+const patchRow = async (h, set, id, body) => {+ const res = await h.org.request({ url: `${h.org.origin}/api/data/v9.2/${set}(${id})`, method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });+ assert.ok(res.statusCode < 300, `${set}: ${res.statusCode}`);+};+const verifyRule = (h, spec = twoRules(), view = viewOf(h)) => readerFor(h.sdk, 'contoso_configured').configuration(spec, undefined, view);+const ruleCheck = (checks) => checks.find((c) => c.kind === 'duplicateRule' && c.name === 'definition');+const setCriteria = (h, row, column) => patchRow(h, 'duplicateruleconditions', row.duplicateruleconditionid, { baseattributename: column, matchingattributename: column });+const assertBuildStops = async (h) => {+ const out = await pass(h, twoRules());+ assert.equal(out.halt && out.halt.code, 'configuration-edit-unsupported', out.halt && out.halt.message);+ assert.equal(out.halt.phase, 'preflight');+ assert.deepEqual(out.sent, [], 'nothing is sent');+};++test('verify fails a protected rule whose bound condition rows swapped their criteria, naming the conditions; the build refuses it too', async () => {+ const h = await harness();+ await created(h, twoRules());+ const e = conditionRow(h, 'emailaddress1');+ const l = conditionRow(h, 'lastname');+ await setCriteria(h, e, 'lastname');+ await setCriteria(h, l, 'emailaddress1');+ const mark = h.org.requests.length;+ const check = ruleCheck(await verifyRule(h));+ assert.equal(check.ok, false, 'the same rule the build refuses must not verify');+ assert.equal(check.code, 'DRIFT');+ assert.deepEqual(check.fields, ['/conditions', '/conditions/e', '/conditions/l']);+ assert.deepEqual(writesSince(h, mark), [], 'verify sends nothing');+ await assertBuildStops(h);+});++// The complete verify output for the swapped state without the opt-in, as the unchanged code produces it for this org: every kind's checks.+const PLAIN_SWAPPED_OUTPUT = [+ { kind: 'environmentVariable', key: 'contoso_ApiBase', name: 'definition', ok: true },+ { kind: 'customApi', key: 'contoso_Calc', name: 'definition', ok: true },+ { kind: 'customApi', key: 'contoso_Calc', name: 'implementation', ok: false, code: 'CUSTOM_API_IMPLEMENTATION_UNPROVEN' },+ { kind: 'duplicateRule', key: 'email', name: 'definition', ok: true },+ { kind: 'duplicateRule', key: 'email', name: 'publication', ok: true },+];+test('verify still passes an unchanged protected rule, and name lookup (no opt-in) passes a real swap exactly as before', async () => {+ const h = await harness();+ await created(h, twoRules());+ assert.deepEqual(ruleCheck(await verifyRule(h)), { kind: 'duplicateRule', key: 'email', name: 'definition', ok: true });+ // Both rows are taken before either is changed: the second lookup would otherwise find the first row again.+ const e = conditionRow(h, 'emailaddress1');+ const l = conditionRow(h, 'lastname');+ await setCriteria(h, e, 'lastname');+ await setCriteria(h, l, 'emailaddress1');+ assert.deepEqual([e, l].map((r) => r.baseattributename), ['lastname', 'emailaddress1'], 'the rows really are swapped');+ const { configurationIdentity, ...plain } = twoRules();+ assert.equal(configurationIdentity, 'stable-v1');+ assert.deepEqual(await verifyRule(h, plain), PLAIN_SWAPPED_OUTPUT, 'name lookup judges by content: the complete output is what it was before');+});++test('a protected rule whose bound condition was deleted and made again still fails verify as not found, and a real criteria change is still drift', async () => {+ const h = await harness();+ await created(h, twoRules());+ const e = conditionRow(h, 'emailaddress1');+ const ruleId = e._regardingobjectid_value;+ const gone = await h.org.request({ url: `${h.org.origin}/api/data/v9.2/duplicateruleconditions(${e.duplicateruleconditionid})`, method: 'DELETE', headers: {} });+ assert.ok(gone.statusCode < 300);+ await insertRow(h.org, 'duplicateruleconditions', { baseattributename: 'emailaddress1', matchingattributename: 'emailaddress1', operatorcode: e.operatorcode, '[email protected]': `/duplicaterules(${ruleId})` });+ const remade = ruleCheck(await verifyRule(h));+ assert.equal(remade.code, B.NOT_FOUND_CODE, 'a bound row is never replaced by a namesake');+ assert.equal(remade.fields, undefined);+ const h2 = await harness();+ await created(h2, twoRules());+ await setCriteria(h2, conditionRow(h2, 'lastname'), 'firstname');+ const changed = ruleCheck(await verifyRule(h2));+ assert.equal(changed.ok, false);+ assert.equal(changed.code, 'DRIFT');+ assert.ok(changed.fields.includes('/conditions') && changed.fields.includes('/conditions/l') && !changed.fields.includes('/conditions/e'), changed.fields.join(','));+ await assertBuildStops(h2);+});++// Verify and the build's preflight judge a bound protected rule by one function (judgeBoundShape + editVerdict), so for every state+// of the rule they must agree: verify passes exactly when the preflight halts nothing for it. Each state runs verify, then the+// preflight, on the same fake org and binding store.+const addRow = (h, column, over = {}) => {+ const sample = conditionRow(h, 'emailaddress1');+ return insertRow(h.org, 'duplicateruleconditions', {+ baseattributename: column, matchingattributename: column, operatorcode: sample.operatorcode, ignoreblankvalues: false,+ '[email protected]': `/duplicaterules(${sample._regardingobjectid_value})`, ...over,+ });+};+const SWAP = async (h) => { const e = conditionRow(h, 'emailaddress1'); const l = conditionRow(h, 'lastname'); await setCriteria(h, e, 'lastname'); await setCriteria(h, l, 'emailaddress1'); };+const withConditions = (conditions) => configSpec(rule({ conditions }));+const E = TWO_CONDITIONS[0];+const L = TWO_CONDITIONS[1];+const STATES = [+ { name: 'unchanged', pass: true },+ { name: 'reordered in the declaration', spec: () => withConditions([L, E]), pass: true },+ { name: 'a single condition', base: configSpec(), spec: () => configSpec(), pass: true },+ { name: 'swapped criteria', change: SWAP, pass: false, fields: ['/conditions', '/conditions/e', '/conditions/l'] },+ { name: 'a changed criterion', change: (h) => setCriteria(h, conditionRow(h, 'lastname'), 'firstname'), pass: false, fields: ['/conditions', '/conditions/l'] },+ { name: 'a renamed key', spec: () => withConditions([{ ...E, key: 'e2' }, L]), pass: false, fields: ['/conditions', '/conditions/e2'] },+ { name: 'a declared condition added', spec: () => withConditions([...TWO_CONDITIONS, { key: 'f', column: 'firstname', match: 'exact' }]), pass: false, fields: ['/conditions', '/conditions/f'] },+ { name: 'a declared condition removed', spec: () => withConditions([E]), pass: false, fields: ['/conditions'] },+ { name: 'an extra server row', change: (h) => addRow(h, 'firstname'), pass: false, fields: ['/conditions'] },+ { name: 'a hand-added duplicate of a bound condition declared under a new key', change: (h) => addRow(h, 'emailaddress1'), spec: () => withConditions([...TWO_CONDITIONS, { key: 'x', column: 'emailaddress1', match: 'exact' }]), pass: false, fields: ['/conditions', '/conditions/x'] },+ { name: 'conditions omitted over bound ones', spec: () => configSpec(rule({ conditions: undefined })), pass: false, fields: ['/conditions'] },+ { name: 'a rule field changed by hand', change: (h) => patchRow(h, 'duplicaterules', h.org.rows('duplicaterules')[0].duplicateruleid, { name: 'Renamed by hand' }), pass: false, fields: ['/name'] },+ { name: 'a changed name and swapped criteria', change: SWAP, spec: () => configSpec(rule({ name: 'Other name', conditions: TWO_CONDITIONS })), pass: false, fields: ['/name', '/conditions', '/conditions/e', '/conditions/l'] },+ { name: 'a changed name and a declared condition added', spec: () => configSpec(rule({ name: 'Other name', conditions: [...TWO_CONDITIONS, { key: 'f', column: 'firstname', match: 'exact' }] })), pass: false, fields: ['/name', '/conditions', '/conditions/f'] },+ { name: 'a changed name and a declared condition removed', spec: () => configSpec(rule({ name: 'Other name', conditions: [E] })), pass: false, fields: ['/name', '/conditions'] },+ { name: 'a hand-added row declared under two new keys (the comparison cannot pair them)', base: configSpec(), change: (h) => addRow(h, 'lastname'), spec: () => withConditions([E, { key: 'l', column: 'lastname', match: 'exact' }, { key: 'l2', column: 'lastname', match: 'exact' }]), pass: false, fields: ['/conditions', '/conditions/l', '/conditions/l2'] },+ { name: 'another matching table', spec: () => configSpec(rule({ matchingEntity: 'account', conditions: TWO_CONDITIONS })), pass: false, fields: ['/matchingEntity'] },+ { name: 'swapped criteria and a status change', change: SWAP, spec: () => configSpec(rule({ status: 'unpublished', conditions: TWO_CONDITIONS })), pass: false, fields: ['/conditions', '/conditions/e', '/conditions/l', '/status'] },+ { name: 'a bound row deleted', change: async (h) => { const row = conditionRow(h, 'lastname'); const res = await h.org.request({ url: `${h.org.origin}/api/data/v9.2/duplicateruleconditions(${row.duplicateruleconditionid})`, method: 'DELETE', headers: {} }); assert.ok(res.statusCode < 300); }, pass: false, code: B.NOT_FOUND_CODE },+ { name: 'an unpublished bound rule without conditions', base: configSpec(rule({ status: 'unpublished', conditions: [] })), spec: () => configSpec(rule({ status: 'unpublished', conditions: [] })), pass: true },+];++async function agreeOn(state) {+ const h = await harness();+ await created(h, state.base || twoRules());+ if (state.change) await state.change(h);+ const spec = state.spec ? state.spec() : state.base || twoRules();+ const mark = h.org.requests.length;+ const check = ruleCheck(await verifyRule(h, spec));+ assert.deepEqual(writesSince(h, mark), [], `${state.name}: verify sends nothing`);+ const out = await pass(h, spec);+ const halted = out.halt !== null;+ assert.equal(check.ok === true, !halted, `${state.name}: verify ${check.ok ? 'passes' : `fails ${check.code}`}, the preflight ${halted ? `halts ${out.halt.code}` : 'does not halt'}`);+ assert.equal(check.ok === true, state.pass, state.name);+ if (state.fields) { assert.equal(check.code, 'DRIFT', `${state.name}: ${check.code}`); assert.deepEqual(check.fields, state.fields, state.name); }+ if (state.code) { assert.equal(check.code, state.code, state.name); assert.equal(out.halt.code, state.code, state.name); }+ if (halted) assert.deepEqual(out.sent, [], `${state.name}: a halted build sent nothing`);+}++test('verify and the build preflight agree on every state of a bound protected rule, and verify never writes', async () => {+ // Every state runs, so one failure does not hide the next.+ const failures = [];+ for (const state of STATES) {+ try { await agreeOn(state); } catch (error) { failures.push(String(error.message).split('\n').filter(Boolean).slice(0, 3).join(' | ').slice(0, 300)); }+ }+ assert.deepEqual(failures, [], 'every state agrees');});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/dashboard-creation-recovery-real-bundle.test.js b/plugins/model-apps/scripts/tests/dashboard-creation-recovery-real-bundle.test.jsindex de53b9085..92138fbbe 100644--- a/plugins/model-apps/scripts/tests/dashboard-creation-recovery-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/dashboard-creation-recovery-real-bundle.test.js@@ -28,6 +28,7 @@ const assert = require('node:assert/strict');const fs = require('node:fs');const path = require('node:path');const { makeTempDir } = require('./helpers/temp-dirs.js');+const { shortRenameWait } = require('./helpers/short-rename-wait.js');const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');const { createLifecycleHarness } = require('./helpers/lifecycle-harness.js');const { createMakerSdk, createNodeWorkspaceStorage } = require('../lib/maker-sdk.js');@@ -727,6 +728,7 @@ const BAD_RECORDS = [fs.linkSync(elsewhere, file);}, /could not be read/],['unwritable', (file, env, t) => {+ shortRenameWait(t);const rename = fs.renameSync;t.mock.method(fs, 'renameSync', function renameSync(from, to, ...rest) {if (path.resolve(String(to)) === path.resolve(file)) throw Object.assign(new Error(`EACCES: permission denied, rename '${from}' -> '${to}'`), { code: 'EACCES' });diff --git a/plugins/model-apps/scripts/tests/halt-retry-policy.test.js b/plugins/model-apps/scripts/tests/halt-retry-policy.test.jsindex 4c17c3d48..387fa9d79 100644--- a/plugins/model-apps/scripts/tests/halt-retry-policy.test.js+++ b/plugins/model-apps/scripts/tests/halt-retry-policy.test.js@@ -127,12 +127,15 @@ const POLICY = {// The sites whose code is an expression, on purpose: the code is decided at run time, so the policy cannot be read off a literal.const DYNAMIC = [{ file: 'lib/sdk-build.js', expr: 'stopCode', kind: 'by-failure', what: 'a declared artifact that did not settle (managedStop): the code of its own first finding; never retried, save an identity read that met the metadata-cache lag of a table this invocation created (isFreshTableReadLag, #796), which the build\'s bounded retry rides out' },- { file: 'lib/entity-provision.js', expr: "(err && err.code) || 'sdk-error'", kind: 'by-failure', what: 'the runner wraps every failed step with the code of what failed' },+ { file: 'lib/entity-provision.js', expr: 'shown.code', kind: 'by-failure', what: 'the runner wraps every failed step with the code of what failed (command-state-contract.js checkedDisplay: the error\'s own, or `sdk-error`; a table publication\'s error in a build with commandStates keeps its own only when it has a system code\'s shape)' },{ file: 'lib/entity-provision.js', expr: 'sdkCode', kind: 'by-failure', what: 'a push the SDK refused by value, with the code the SDK gave' },{ file: 'lib/sdk-build.js', expr: 'verdict.code', kind: 'never', what: 'the navigation verdict (app-navigation-empty): a re-run reads the same spec' },{ file: 'lib/sdk-build.js', expr: 'incomplete[0].code', kind: 'never', what: 'the end of a build that ran every phase and saved its changes, but left a publication owed or an exact Main-form list unproven (error.incomplete): running the phases again would push the saved change again and cannot settle what is withheld or unknown; the maker re-runs once the cause is cleared' },{ file: 'build-model-app.js', expr: 'err.code', kind: 'never', what: 'a halt that stops service writes (the retirement the build could not confirm, managed-not-settled), said again on a later attempt of the run (stoppedAfterEarlierAttempts): the code of the halt it says again; never retried, as that halt is not' },{ file: 'lib/configuration-build.js', expr: 'haltCode', kind: 'never', what: 'the configuration step left work undone (configuration-incomplete, a refusal or an unknown outcome): an unknown write is inspected, never replayed' },+ { file: 'lib/command-state-run.js', expr: 'error.code', kind: 'never', what: 'a commandStates refusal or unknown outcome (commandStateHalt, a CommandStateError: approval required or stale, version conflict, not confirmed, publish unconfirmed, …): an unknown write is read back, never sent again, and a refusal reads the same rows again (command-state-build.test.js)' },+ { file: 'lib/sdk-build.js', expr: 'commandStateModeOfRun.code', kind: 'never', what: 'a run that cannot apply commandStates (command-state-phase-unsupported, -publish-required, -keyed-unsupported), refused before anything is read or written: the same options stop again' },+ { file: 'lib/sdk-build.js', expr: 'COMMAND_STATE_CODES.legacyCreateConflict', kind: 'never', what: 'commands[] would create a bar on a table whose rows commandStates edits (command-state-legacy-create-conflict), refused before the create: the same spec stops again' },{ file: 'lib/configuration-build.js', expr: 'preflightCode', kind: 'never', what: 'the protected configuration preflight, before any write (configuration-edit-unsupported, create-identity-unverified, create-identity-opt-in-required, managed-settlement-pending for an attempt the binding store holds for an item the App Spec no longer declares, and the other codes of the first item it stops): the same plan stops again' },];// Object literals that carry `phase`, `code` and `recoverable` and are not halts.diff --git a/plugins/model-apps/scripts/tests/helpers/command-state-build-harness.js b/plugins/model-apps/scripts/tests/helpers/command-state-build-harness.jsnew file mode 100644index 000000000..d6b74bd89--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/command-state-build-harness.js@@ -0,0 +1,128 @@+'use strict';+// The build harness of the commandStates tests (command-state-build.test.js, command-state-taint.test.js): the build's own entry point+// (lib/sdk-build.js runSdkBuild) over the light mock SDK (helpers/mock-sdk.js), whose raw client publishes the tables before the app, and the+// command rows of the fake org (helpers/command-state-org.js) reached through the real raw client (createAzHttpClient) and the feature's own+// transport, so the retry and send-once behaviour under test is the shipped one.++const assert = require('node:assert');+const { inOwnFolder } = require('./own-app-folder.js');+const runSdkBuild = inOwnFolder(require('../../lib/sdk-build.js').runSdkBuild);+const { makeSimpleMockSdk } = require('./mock-sdk.js');+const { createAzHttpClient } = require('../../lib/sdk-http-client.js');+const { createCommandStateTransport, commandStateSendOnce } = require('../../lib/command-state-transport.js');+const { createCommandStateOrg, commandRow, ORIGIN } = require('./command-state-org.js');+const { validateAppSpec } = require('../../lib/app-spec.js');++const T = 'new_ticket';+const MD = '44444444-4444-4444-8444-444444444444';+const ROW = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';+const API = `${ORIGIN}/api/data/v9.2`;+const HIDE = { entity: T, location: 'MainTab', scope: 'table', rowId: ROW, hidden: true };+const APPLY = { apply: true, publish: true };++function specFor(states = [HIDE], extra = {}) {+ const spec = {+ minimumPluginVersion: '2.24.0',+ solution: { uniqueName: 'ContosoSD', displayName: 'Contoso SD', publisherPrefix: 'new' },+ app: { name: 'Support', uniqueName: 'contoso_Support' },+ entities: [{ schemaName: T, displayName: 'Ticket', primaryAttribute: { schemaName: 'new_subject', displayName: 'Subject' } }],+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Records', subAreas: [{ entity: T, title: 'Tickets' }] }] }] },+ ...(states ? { commandStates: states } : {}),+ ...extra,+ };+ assert.deepStrictEqual(validateAppSpec(spec).errors, [], 'the fixture is a valid spec');+ return spec;+}++// The tables a PublishXml body names: { "ParameterXml": "<importexportxml><entities><entity>new_ticket</entity></entities></importexportxml>" }+const tablesOf = (body) => [...String((body && body.ParameterXml) || '').matchAll(/<entity>([^<]+)<\/entity>/g)].map((m) => m[1]);++// `publishAnswer(tables)` may answer one publish otherwise (a refusal of one table, say); undefined keeps `publishStatus`.+// `barrier`: the publication barrier the build is given (publicationBarrier). With one, every publish passes its gate (gateRequest) the+// way the shipped transport's does, so a table the barrier routes is published by the managed publisher under its send permit.+// `adaptSdk(sdk)`: changes the mock SDK each build is given — for a build that finds an existing view to reconcile (findArtifact), or+// whose SDK publication of an artifact answers otherwise (publishArtifact).+function harness({ rows = [commandRow(ROW, T, MD)], publishStatus = 204, onPublish, publishAnswer, barrier, adaptSdk, tables = { [T]: { metadataId: MD } }, ...orgOptions } = {}) {+ const org = createCommandStateOrg({ writable: true, tables, rows, ...orgOptions });+ const client = createAzHttpClient(ORIGIN, { getToken: () => 'test-token', request: org.request, sleep: async () => {}, sendOnce: commandStateSendOnce });+ const transport = createCommandStateTransport({ client, apiUrl: (p) => `${API}${p}` });+ const published = [];+ const send = async (body) => {+ published.push(tablesOf(body));+ if (onPublish) onPublish(tablesOf(body));+ const answer = publishAnswer ? await publishAnswer(tablesOf(body)) : undefined;+ return answer || { status: publishStatus, body: null };+ };+ // The gate reads a request in the transport's shape (lib/dataverse-auth.js makeRequest: { method, url, body } with the body as text,+ // answered { statusCode, headers, body }); the SDK's Dataverse client answers { status, headers, body } with the body parsed.+ const gated = barrier ? barrier.gateRequest(async (req) => {+ const answer = await send(JSON.parse(req.body));+ const text = answer.body == null ? '' : typeof answer.body === 'string' ? answer.body : JSON.stringify(answer.body);+ return { statusCode: answer.status, headers: {}, body: text };+ }) : null;+ const mockSdk = () => {+ const { sdk, calls } = makeSimpleMockSdk();+ sdk.dataverse = {+ apiUrl: (p) => `${API}${p}`,+ post: async (url, body) => {+ if (!gated) return send(body);+ const res = await gated({ method: 'POST', url: `${API}${url}`, headers: {}, body: JSON.stringify(body) });+ let parsed = res.body;+ try { parsed = res.body ? JSON.parse(res.body) : null; } catch { /* a body that is not JSON is answered as its text */ }+ return { status: res.statusCode, headers: res.headers || {}, body: parsed };+ },+ // The managed publisher needs a client that can read layers (publishManagedScope). The stores these tests give it hold no managed+ // group, so it reads none; a read is a fixture error, not a service answer.+ ...(gated ? { get: async (url) => { throw new Error(`the harness reads no layers (${url})`); } } : {}),+ };+ if (adaptSdk) adaptSdk(sdk);+ return { sdk, calls };+ };+ const build = async (spec, opts = {}) => {+ const { sdk, calls } = mockSdk();+ const warnings = [];+ const run = { sdk, env: ORIGIN, commandStateTransport: transport, emit: () => {}, warn: (w) => warnings.push(String(w)), ...opts };+ try {+ return { res: await runSdkBuild(spec, run), calls, warnings };+ } catch (error) {+ return { error, calls, warnings };+ }+ };+ // The approvals a dry run prints, exactly as an author would pass them back.+ const approve = async (spec) => {+ const { res, error } = await build(spec, { apply: false });+ assert.ifError(error);+ const plan = res.commandStatePlan;+ return { plan, approvals: { rows: new Set(plan.rows.map((r) => r.approval).filter(Boolean)), tables: new Set(plan.tables.map((t) => t.token)) } };+ };+ const patches = () => org.requests.filter((r) => r.method === 'PATCH');+ return { org, build, approve, published, patches, transport, mockSdk };+}++// The build's own entry (build-model-app.js buildModelApp) with its durable journal, for what a halt leaves on disk and says on the console.+async function buildWithJournal(h, spec, approvals, engineOptions = {}) {+ const fs = require('node:fs');+ const path = require('node:path');+ const { buildModelApp } = require('../../build-model-app.js');+ const { openJournal } = require('../../lib/build-journal.js');+ const { makeTempDir } = require('./temp-dirs.js');+ const engine = require('../../lib/sdk-build.js').runSdkBuild;+ const workspaceDir = makeTempDir('cs-journal-');+ const journal = openJournal(path.join(workspaceDir, 'logs'));+ const said = [];+ const logged = [];+ let result;+ const { sdk } = h.mockSdk();+ let caught;+ try {+ result = await buildModelApp(spec, { apply: true, publish: true, env: ORIGIN, workspaceDir, commandStateApprovals: approvals }, {+ sdk, journal, log: (m) => logged.push(String(m)), warn: (m) => said.push(String(m)), sleep: async () => {},+ runBuild: (s, o) => engine(s, { ...o, commandStateTransport: h.transport, ...engineOptions }),+ });+ } catch (error) {+ caught = error;+ }+ return { caught, result, said: said.join('\n'), logged: logged.join('\n'), log: fs.readFileSync(journal.path, 'utf8'), status: fs.readFileSync(journal.statusPath, 'utf8') };+}++module.exports = { T, MD, ROW, API, HIDE, APPLY, specFor, tablesOf, harness, buildWithJournal };diff --git a/plugins/model-apps/scripts/tests/helpers/command-state-org.js b/plugins/model-apps/scripts/tests/helpers/command-state-org.jsnew file mode 100644index 000000000..d3fc7ed7f--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/command-state-org.js@@ -0,0 +1,154 @@+'use strict';+// A fake Dataverse that answers the reads of the command-state feature in the platform's shapes, for the real raw client+// (`createAzHttpClient`, lib/sdk-http-client.js) and the real vendored SDK's API root:+// GET /appmodules?$select=appmoduleid,uniquename&$filter=uniquename eq '<name>'+// GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq <id>+// GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <layer> and componenttype eq 1+// GET /EntityDefinitions(LogicalName='<table>')?$select=MetadataId,EntitySetName+// GET /EntityDefinitions(<metadataId>)?$select=LogicalName,MetadataId+// GET /EntityDefinitions(LogicalName='appaction')?$select=IsOptimisticConcurrencyEnabled+// GET /appactions?$select=...&$filter=contextvalue eq '<table>' pages of `pageSize` rows, continued by an ABSOLUTE @odata.nextLink+// GET /appactions(<id>)?$select=... one row, or 404 with 0x80040217+// PATCH /appactions(<id>) (only with `writable`) If-Match must equal the row's version, else 412 0x80060882; a missing row+// is 404 0x80040217; the flags are stored, the version goes up by one, 204+// Every request is recorded (method, the decoded path below the API root, the absolute url, the headers, the body); a request it has no answer for+// is recorded in `unexpected` and answered 400. `overrides(req)` may answer a request first (return a `{ statusCode, body }` or undefined), and+// `afterPatch(req, row)` may replace the answer to a PATCH that was stored (e.g. a cut connection or a 503 after the commit).++const ORIGIN = 'https://contoso.crm.dynamics.com';+const APP_ID = '11111111-1111-4111-8111-111111111111';+const LAYER_ID = '22222222-2222-4222-8222-222222222222';+const OTHER_APP_ID = '33333333-3333-4333-8333-333333333333';++const SELECT_ALL = [+ 'appactionid', 'name', 'uniquename', 'buttonlabeltext', 'context', 'contextvalue', '_contextentity_value', '_appmoduleid_value', 'location',+ 'type', 'origin', 'statecode', 'statuscode', 'ismanaged', 'iscustomizable', '_parentappactionid_value', 'hidden', 'isdisabled', 'visibilitytype',+ 'visibilityformulacomponentlibrary', '_visibilityformulacomponentlibraryid_value', 'visibilityformulacomponentname', 'visibilityformulafunctionname',+ 'onclickeventtype',+];++// An ordinary top-level, table-scoped, active, unmanaged JavaScript button on a table's form bar, as the platform answers it; `extra` overrides.+function commandRow(id, table, metadataId, extra = {}) {+ return {+ '@odata.etag': 'W/"1001"',+ appactionid: id,+ name: `contoso_${id.slice(0, 4)}`,+ uniquename: `contoso_${id.slice(0, 4)}`,+ buttonlabeltext: 'Escalate',+ context: 1,+ contextvalue: table,+ _contextentity_value: metadataId,+ _appmoduleid_value: null,+ location: 0,+ type: 0,+ origin: 0,+ statecode: 0,+ statuscode: 1,+ ismanaged: false,+ iscustomizable: { Value: true, CanBeChanged: true, ManagedPropertyLogicalName: 'iscustomizableanddeletable' },+ _parentappactionid_value: null,+ hidden: false,+ isdisabled: false,+ // What the platform stores on a button a plain commands[] build wrote: a present null, not 0.+ visibilitytype: null,+ visibilityformulacomponentlibrary: null,+ _visibilityformulacomponentlibraryid_value: null,+ visibilityformulacomponentname: null,+ visibilityformulafunctionname: null,+ onclickeventtype: 2,+ ...extra,+ };+}++const json = (statusCode, body, headers = {}) => ({ statusCode, headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body) });+const notFound = () => json(404, { error: { code: '0x80040217', message: 'appaction With Id = x Does Not Exist' } });++/**+ * @param {object} [options]+ * @param {Array<{ appmoduleid: string, uniquename: string }>} [options.apps]+ * @param {Object<string, { metadataId: string, entitySetName?: string, inApp?: boolean }>} [options.tables]+ * @param {object[]} [options.rows] - appaction rows (commandRow)+ * @param {boolean|null|'omit'} [options.concurrency] - IsOptimisticConcurrencyEnabled; 'omit' leaves it out of the answer+ * @param {number} [options.pageSize]+ * @param {(req: object) => object|undefined} [options.overrides]+ * @param {boolean} [options.writable] - answer the row PATCH+ * @param {(req: object, row: object) => object|undefined} [options.afterPatch]+ */+function createCommandStateOrg({+ apps = [{ appmoduleid: APP_ID, uniquename: 'contoso_Support' }], tables = {}, rows = [], concurrency = true, pageSize = 2, overrides, writable = false, afterPatch,+} = {}) {+ const requests = [];+ const unexpected = [];+ const page = (all, req, base) => {+ const at = Number((/[&?]\$skiptoken=(\d+)/.exec(req.path) || [])[1] || 0);+ const value = all.slice(at, at + pageSize);+ const body = { value };+ if (at + pageSize < all.length) body['@odata.nextLink'] = `${base}&$skiptoken=${at + pageSize}`;+ return json(200, body);+ };+ async function request(opts) {+ const url = new URL(opts.url);+ const apiAt = url.pathname.search(/\/api\/data\/v9\.\d+/);+ const prefix = apiAt === -1 ? '' : /\/api\/data\/v9\.\d+/.exec(url.pathname)[0];+ const pathOnly = apiAt === -1 ? url.pathname : url.pathname.slice(apiAt + prefix.length);+ let body = opts.body;+ if (typeof body === 'string' || Buffer.isBuffer(body)) { try { body = JSON.parse(String(body)); } catch { /* kept as sent */ } }+ const req = { method: opts.method, url: opts.url, origin: url.origin, path: decodeURIComponent(pathOnly + url.search), headers: opts.headers || {}, body };+ requests.push(req);+ if (overrides) {+ const answer = await overrides(req);+ if (answer) return answer;+ }+ const p = req.path;+ let m;+ if (writable && req.method === 'PATCH' && (m = /^\/appactions\(([0-9a-f-]{36})\)$/.exec(p))) {+ const row = rows.find((r) => r.appactionid === m[1]);+ if (!row) return notFound();+ const ifMatch = Object.entries(req.headers).find(([k]) => k.toLowerCase() === 'if-match');+ if (!ifMatch || ifMatch[1] !== row['@odata.etag']) return json(412, { error: { code: '0x80060882', message: 'The version of the existing record does not match the RowVersion property provided.' } });+ const keys = req.body && typeof req.body === 'object' ? Object.keys(req.body) : [];+ if (!keys.length || keys.some((k) => k !== 'hidden' && k !== 'isdisabled')) { unexpected.push(req); return json(400, { error: { code: '0x0', message: 'unexpected body' } }); }+ for (const k of keys) row[k] = req.body[k];+ row['@odata.etag'] = `W/"${Number(/\d+/.exec(row['@odata.etag'])[0]) + 1}"`;+ const replaced = afterPatch ? await afterPatch(req, row) : undefined;+ return replaced || { statusCode: 204, headers: {}, body: '' };+ }+ if (req.method !== 'GET') { unexpected.push(req); return json(400, { error: { code: '0x0', message: 'unexpected write' } }); }+ if ((m = /^\/appmodules\?\$select=appmoduleid,uniquename&\$filter=uniquename eq '(.*)'$/.exec(p))) {+ const name = m[1].replace(/''/g, "'").toLowerCase();+ return json(200, { value: apps.filter((a) => a.uniquename.toLowerCase() === name) });+ }+ if ((m = /^\/appmodules\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublishedMultiple\(\)\?\$select=appmoduleid,appmoduleidunique,componentstate&\$filter=appmoduleid eq ([0-9a-f-]{36})$/.exec(p))) {+ return json(200, { value: apps.filter((a) => a.appmoduleid === m[1]).map((a) => ({ appmoduleid: a.appmoduleid, appmoduleidunique: LAYER_ID, componentstate: 0 })) });+ }+ if ((m = /^\/appmodulecomponents\?\$select=objectid,componenttype&\$filter=_appmoduleidunique_value eq ([0-9a-f-]{36}) and componenttype eq 1$/.exec(p))) {+ const value = m[1] === LAYER_ID ? Object.values(tables).filter((t) => t.inApp !== false).map((t) => ({ objectid: t.metadataId, componenttype: 1 })) : [];+ return json(200, { value });+ }+ if (p === "/EntityDefinitions(LogicalName='appaction')?$select=IsOptimisticConcurrencyEnabled") {+ return json(200, concurrency === 'omit' ? { MetadataId: 'x' } : { IsOptimisticConcurrencyEnabled: concurrency });+ }+ if ((m = /^\/EntityDefinitions\(LogicalName='([a-z0-9_]+)'\)\?\$select=MetadataId,EntitySetName$/.exec(p))) {+ const t = tables[m[1]];+ return t ? json(200, { MetadataId: t.metadataId, EntitySetName: t.entitySetName || `${m[1]}s` }) : json(404, { error: { code: '0x80060888', message: 'no such table' } });+ }+ if ((m = /^\/EntityDefinitions\(([0-9a-f-]{36})\)\?\$select=LogicalName,MetadataId$/.exec(p))) {+ const name = Object.keys(tables).find((k) => tables[k].metadataId === m[1]);+ return name ? json(200, { LogicalName: name, MetadataId: m[1] }) : json(404, { error: { code: '0x80060888', message: 'no such table' } });+ }+ if ((m = /^\/appactions\?\$select=([a-z_,]+)&\$filter=contextvalue eq '([a-z0-9_]+)'(&\$skiptoken=\d+)?$/.exec(p))) {+ const all = rows.filter((r) => typeof r.contextvalue === 'string' && r.contextvalue.toLowerCase() === m[2]);+ const base = `${url.origin}${prefix}/appactions?$select=${m[1]}&$filter=contextvalue eq '${m[2]}'`;+ return page(all, req, base);+ }+ if ((m = /^\/appactions\(([0-9a-f-]{36})\)\?\$select=[a-z_,]+$/.exec(p))) {+ const row = rows.find((r) => r.appactionid === m[1]);+ return row ? json(200, row) : notFound();+ }+ unexpected.push(req);+ return json(400, { error: { code: '0x0', message: 'unexpected request' } });+ }+ return { request, requests, unexpected, writes: () => requests.filter((r) => r.method !== 'GET') };+}++module.exports = { createCommandStateOrg, commandRow, json, notFound, ORIGIN, APP_ID, LAYER_ID, OTHER_APP_ID, SELECT_ALL };diff --git a/plugins/model-apps/scripts/tests/helpers/short-rename-wait.js b/plugins/model-apps/scripts/tests/helpers/short-rename-wait.jsnew file mode 100644index 000000000..369677761--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/short-rename-wait.js@@ -0,0 +1,23 @@+'use strict';+// A rename refused with EPERM, EACCES or EBUSY is waited out on Windows (lib/rename-retry.js: 5 s a rename, 30 s in all for the+// process). A test that keeps a rename failing for good, to see what the caller does with a lock that stays, uses this to wait a+// moment instead. It starts the test from a fresh process total and puts both the budget and the total back when the test ends, so+// no test leaves a spent or shortened budget to the next. Elsewhere there is no wait, so it changes nothing.+const { setDefaultBudgetMs, setProcessWaitedMs } = require('../../lib/rename-retry.js');++function shortRenameWait(t, ms = 40) {+ const previousBudget = setDefaultBudgetMs(ms);+ const previousWaited = setProcessWaitedMs(0);+ t.after(() => {+ setDefaultBudgetMs(previousBudget);+ setProcessWaitedMs(previousWaited);+ });+}++// A test that exercises the default budgets starts from a fresh process total, and puts the old one back.+function freshRenameWaitTotal(t) {+ const previousWaited = setProcessWaitedMs(0);+ t.after(() => setProcessWaitedMs(previousWaited));+}++module.exports = { shortRenameWait, freshRenameWaitTotal };diff --git a/plugins/model-apps/scripts/tests/list-command-states.test.js b/plugins/model-apps/scripts/tests/list-command-states.test.jsnew file mode 100644index 000000000..4cdc6401e--- /dev/null+++ b/plugins/model-apps/scripts/tests/list-command-states.test.js@@ -0,0 +1,143 @@+'use strict';+// scripts/list-command-states.js end to end: the command line, then the listing through the real SDK bundle (its API root) and the plugin's+// real raw client over a fake Dataverse (helpers/command-state-org.js) — so the requests counted are the ones that would reach the wire.+const test = require('node:test');+const assert = require('node:assert');+const path = require('node:path');+const { loadCli } = require('./helpers/cli-harness.js');+const realAuth = require('../lib/dataverse-auth.js');+const realHttp = require('../lib/sdk-http-client.js');+const { listCommandStates } = require('../list-command-states.js');+const { createCommandStateOrg, commandRow, json, ORIGIN, APP_ID, OTHER_APP_ID } = require('./helpers/command-state-org.js');++const SCRIPT = path.resolve(__dirname, '..', 'list-command-states.js');+const API = `${ORIGIN}/api/data/v9.0`;+const TICKET = 'aaaaaaaa-0000-4000-8000-000000000001';+const ORDER = 'aaaaaaaa-0000-4000-8000-000000000002';+const NOTE = 'aaaaaaaa-0000-4000-8000-000000000003';+const TABLES = { contoso_ticket: { metadataId: TICKET }, contoso_order: { metadataId: ORDER }, contoso_note: { metadataId: NOTE, inApp: false } };+const id = (n) => `bbbbbbbb-0000-4000-8000-${String(n).padStart(12, '0')}`;+const ROWS = [+ commandRow(id(1), 'contoso_ticket', TICKET, { buttonlabeltext: 'Escalate' }),+ commandRow(id(2), 'contoso_ticket', TICKET, { buttonlabeltext: 'Escalate', _appmoduleid_value: APP_ID, hidden: true }),+ commandRow(id(3), 'contoso_ticket', TICKET, { buttonlabeltext: 'Approve', location: 1, isdisabled: true }),+ commandRow(id(4), 'contoso_ticket', TICKET, { buttonlabeltext: 'Bulk', location: 2, _appmoduleid_value: OTHER_APP_ID }),+ commandRow(id(5), 'contoso_ticket', TICKET, { buttonlabeltext: 'Header', location: 4 }),+ commandRow(id(6), 'contoso_order', ORDER, { buttonlabeltext: 'Ship', statecode: 1, statuscode: 2 }),+ commandRow(id(7), 'contoso_note', NOTE, { buttonlabeltext: 'Pin' }),+];+const clientFor = (org) => realHttp.createAzHttpClient(ORIGIN, { getToken: () => 'test-token', request: org.request, sleep: async () => {} });++async function run(argv, org = createCommandStateOrg({ tables: TABLES, rows: ROWS })) {+ const emitted = [];+ const requires = {+ './lib/dataverse-auth.js': {+ ...realAuth,+ emitResult: (ok, payload) => {+ emitted.push({ ok, payload });+ const exit = new Error(`process.exit(${ok ? 0 : 1})`);+ exit.exitCode = ok ? 0 : 1;+ throw exit;+ },+ },+ './lib/sdk-http-client.js': { ...realHttp, createAzHttpClient: (env) => realHttp.createAzHttpClient(env, { getToken: () => 'test-token', request: org.request, sleep: async () => {} }) },+ };+ const cli = loadCli(SCRIPT, { requires, argv });+ let exitCode = 0;+ try {+ await cli.main();+ } catch (err) {+ if (typeof err.exitCode !== 'number') throw err;+ exitCode = err.exitCode;+ }+ return { org, exitCode, emitted, stdout: cli.stdoutText(), stderr: cli.stderrText(), payload: emitted.length ? emitted[0].payload : undefined };+}++// --- the command line ------------------------------------------------------------------------------------------++test('a usage error or a write flag prints nothing on stdout, names the flag on stderr, and reads nothing', async () => {+ const cases = [+ [[], /--env is required/],+ [['--env', ORIGIN], /--app is required/],+ [['--env', 'http://contoso.crm.dynamics.com', '--app', 'a'], /https/],+ [['--env', ORIGIN, '--app', 'a', '--location', 'Grid'], /--location must be one of MainTab, HomeTab, ContextualTab/],+ [['--env', ORIGIN, '--app', 'a', '--entity', 'not a table'], /--entity 'not a table' is not a table's logical name/],+ [['--env', ORIGIN, '--app', 'a', '--table', 'x'], /--table/],+ [['--env', ORIGIN, '--app', 'a', 'extra'], /unexpected argument 'extra'/],+ [['--env', ORIGIN, '--app', 'a', '--apply'], /--apply is not accepted: list-command-states only reads/],+ [['--env', ORIGIN, '--app', 'a', '--publish'], /--publish is not accepted/],+ [['--env', ORIGIN, '--app', 'a', '--authorize=overwrite:x'], /--authorize is not accepted/],+ [['--env', ORIGIN, '--app', 'a', '--yes'], /--yes is not accepted/],+ ];+ for (const [argv, message] of cases) {+ const r = await run(argv);+ assert.strictEqual(r.exitCode, 1, argv.join(' '));+ assert.strictEqual(r.stdout, '', argv.join(' '));+ assert.match(r.stderr, message, argv.join(' '));+ assert.match(r.stderr, /Usage: node scripts\/list-command-states\.js/, argv.join(' '));+ assert.deepStrictEqual(r.org.requests, [], argv.join(' '));+ }+});++test('the listing prints every button of the named table, candidates and excluded rows alike, reading only', async () => {+ const r = await run(['--env', ORIGIN, '--app', 'contoso_Support', '--entity', 'Contoso_Ticket']);+ assert.strictEqual(r.exitCode, 0, r.stderr);+ assert.strictEqual(r.emitted[0].ok, true);+ const out = r.payload;+ assert.deepStrictEqual({ app: out.app, entity: out.entity, optimisticConcurrency: out.optimisticConcurrency, tables: out.tables, count: out.count, candidates: out.candidates },+ { app: { uniqueName: 'contoso_Support', appId: APP_ID }, entity: 'contoso_ticket', optimisticConcurrency: true, tables: [{ entity: 'contoso_ticket', metadataId: TICKET, inApp: true }], count: 5, candidates: 2 });+ assert.deepStrictEqual(out.commands.map((c) => [c.bar, c.location, c.caption, c.rowId, c.scope, c.hidden, c.disabled, c.candidate, c.reasons]), [+ ['MainTab', 0, 'Escalate', id(1), 'table', false, false, true, []],+ ['MainTab', 0, 'Escalate', id(2), 'app', true, false, false, ['app-scoped']],+ ['HomeTab', 1, 'Approve', id(3), 'table', false, true, true, []],+ ['ContextualTab', 2, 'Bulk', id(4), 'other-app', false, false, false, ['app-scoped']],+ ['unsupported', 4, 'Header', id(5), 'table', false, false, false, ['location-unsupported']],+ ]);+ assert.deepStrictEqual(out.commands[0].sameCaption, [id(2)]);+ assert.deepStrictEqual(out.commands[1].sameCaption, [id(1)]);+ assert.strictEqual(out.commands[2].sameCaption, undefined);+ assert.ok(r.org.requests.length > 0);+ assert.ok(r.org.requests.every((req) => req.method === 'GET'), 'only reads');+ assert.ok(r.org.requests.every((req) => req.url.startsWith(`${API}/`)), 'only the SDK\u2019s API root on the named origin');+ assert.deepStrictEqual(r.org.unexpected, []);+});++test('without --entity every table of the app is listed, and --location keeps one bar', async () => {+ const org = createCommandStateOrg({ tables: TABLES, rows: ROWS });+ const all = await listCommandStates(ORIGIN, { app: 'contoso_Support' }, clientFor(org));+ assert.deepStrictEqual(all.tables.map((t) => t.entity), ['contoso_order', 'contoso_ticket'], 'the app\u2019s tables, not every table');+ assert.deepStrictEqual(all.commands.map((c) => c.rowId), [id(6), id(1), id(2), id(3), id(4), id(5)]);+ assert.deepStrictEqual(all.commands[0].reasons, ['inactive']);+ assert.strictEqual(all.commands[0].active, false);+ const home = await listCommandStates(ORIGIN, { app: 'contoso_Support', location: 'HomeTab' }, clientFor(createCommandStateOrg({ tables: TABLES, rows: ROWS })));+ assert.deepStrictEqual([home.location, home.commands.map((c) => c.rowId)], ['HomeTab', [id(3)]]);+ // A table that is not one of the app's is listed with that reason, not silently read as if it were.+ const note = await listCommandStates(ORIGIN, { app: 'contoso_Support', entity: 'contoso_note' }, clientFor(createCommandStateOrg({ tables: TABLES, rows: ROWS })));+ assert.deepStrictEqual([note.tables[0].inApp, note.commands.map((c) => [c.rowId, c.candidate, c.reasons])], [false, [[id(7), false, ['table-not-in-app']]]]);+ assert.deepStrictEqual(org.writes(), []);+});++test('with row versions off for the table of commands no button is a candidate, and the listing says so', async () => {+ const out = await listCommandStates(ORIGIN, { app: 'contoso_Support', entity: 'contoso_ticket' }, clientFor(createCommandStateOrg({ tables: TABLES, rows: ROWS, concurrency: false })));+ assert.strictEqual(out.optimisticConcurrency, false);+ assert.strictEqual(out.candidates, 0);+ assert.ok(out.commands.every((c) => c.reasons.includes('version-unavailable')));+});++test('a failed or incomplete read prints ok:false with its code and exits 1, never an empty success', async () => {+ const cases = [+ [{ apps: [] }, 'command-state-context-unverified'],+ [{ concurrency: 'omit' }, 'command-state-version-unavailable'],+ [{ overrides: (req) => (req.path.startsWith('/appactions?') && req.path.includes('$skiptoken=2') ? json(403, { error: { code: '0x80040220', message: 'denied' } }) : undefined) }, 'command-state-row-unreadable'],+ ];+ for (const [options, code] of cases) {+ const r = await run(['--env', ORIGIN, '--app', 'contoso_Support', '--entity', 'contoso_ticket'], createCommandStateOrg({ tables: TABLES, rows: ROWS, ...options }));+ assert.strictEqual(r.exitCode, 1, code);+ assert.strictEqual(r.emitted[0].ok, false, code);+ assert.strictEqual(r.payload.ok, false, code);+ assert.strictEqual(r.payload.code, code);+ assert.strictEqual(typeof r.payload.error, 'string');+ assert.strictEqual(r.payload.commands, undefined, 'no partial list');+ assert.deepStrictEqual(r.org.writes(), []);+ }+});diff --git a/plugins/model-apps/scripts/tests/page-ownership.test.js b/plugins/model-apps/scripts/tests/page-ownership.test.jsindex 2f11c0ccc..da5059e26 100644--- a/plugins/model-apps/scripts/tests/page-ownership.test.js+++ b/plugins/model-apps/scripts/tests/page-ownership.test.js@@ -8,6 +8,7 @@ const { reconcilePageIds } = require('../lib/page-manifest.js');const { runTeardown: realRunTeardown } = require('../lib/sdk-teardown.js');const { runSdkBuild } = require('../lib/sdk-build.js');const { loadCli } = require('./helpers/cli-harness.js');+const { shortRenameWait } = require('./helpers/short-rename-wait.js');const { fakeGenpage } = require('./helpers/fake-genpage.js');const { withPageType } = require('./helpers/page-component-type.js');const { isFormScan, noFormRows } = require('./helpers/form-scan.js');@@ -873,6 +874,7 @@ test('no workspace refuses app deletion when navigation proof cannot be preserve});test('a failed ownership-record write leaves the app and its pages intact', async (t) => {+ shortRenameWait(t);const workspaceDir = workspace();const rename = fs.renameSync;t.mock.method(fs, 'renameSync', (from, to) => {diff --git a/plugins/model-apps/scripts/tests/printers-whole-before-exit.test.js b/plugins/model-apps/scripts/tests/printers-whole-before-exit.test.jsindex 8cdc2b6fd..4f2be6da4 100644--- a/plugins/model-apps/scripts/tests/printers-whole-before-exit.test.js+++ b/plugins/model-apps/scripts/tests/printers-whole-before-exit.test.js@@ -260,7 +260,7 @@ test('genpage-worker-output.js prints a result that quotes the longest path a coconst USAGE_CASES = [['add-page-to-solution.js'], ['ai-preflight.js'], ['apps.js', ['list']], ['build-model-app.js'], ['connector.js', ['operations']],['create-connection-reference.js'], ['dataverse-request.js'], ['download-model-app.js'], ['genpage.js', ['list']], ['list-connections.js'],- ['list-custom-apis.js'], ['list-languages.js'], ['list-tables.js'], ['preview-app.js'], ['preview-form.js'],+ ['list-command-states.js'], ['list-custom-apis.js'], ['list-languages.js'], ['list-tables.js'], ['preview-app.js'], ['preview-form.js'],['promote-intent-pages.js'], ['provision-entities.js'], ['provision-solution.js'], ['solution-settings.js', ['template']], ['teardown-model-app.js'],['verify-model-app.js'], ['write-app-spec-doc.js'], ['write-page-plan.js'],].map(([script, args = []]) => ({ script, args }));@@ -289,7 +289,7 @@ test('every script\'s usage error is what it always was: the message, then the u// scripts that hand the error to emitResult, emitResult's.const THROW_CASES = [['ai-preflight.js'], ['apps.js', ['list']], ['connector.js', ['operations']], ['genpage.js', ['list']], ['genpage-base.js', ['check']], ['genpage-upload.js'],- ['list-languages.js'], ['list-tables.js'], ['build-model-app.js'], ['download-model-app.js'], ['provision-entities.js'], ['provision-solution.js'],+ ['list-command-states.js'], ['list-languages.js'], ['list-tables.js'], ['build-model-app.js'], ['download-model-app.js'], ['provision-entities.js'], ['provision-solution.js'],['teardown-model-app.js'], ['verify-model-app.js'], ['write-app-spec-doc.js'],].map(([script, args = []]) => ({ script, args }));diff --git a/plugins/model-apps/scripts/tests/publish-scope-real-bundle.test.js b/plugins/model-apps/scripts/tests/publish-scope-real-bundle.test.jsindex ef4cd4f3a..089c1a899 100644--- a/plugins/model-apps/scripts/tests/publish-scope-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/publish-scope-real-bundle.test.js@@ -1168,7 +1168,8 @@ for (const [what, damaged] of [// edit that calls the SDK for the app directly — a new path, say — cannot skip it. This reads the engine's source, because that is where a new path would be written.// (The request is made once for what it names, so a run in which the app step has made it cannot show that a LATER writer forgot to ask: this is what shows it.)test('sdk-build.js reaches the SDK for the app only through appWriters, and each writer sends the request before its first write of the app', () => {- const source = fs.readFileSync(path.join(__dirname, '..', 'lib', 'sdk-build.js'), 'utf8');+ // A checkout may give the file CRLF line endings; every pattern below is written for LF.+ const source = fs.readFileSync(path.join(__dirname, '..', 'lib', 'sdk-build.js'), 'utf8').replace(/\r\n/g, '\n');// Code only: a comment may name what it explains.const code = source.split('\n').map((line) => line.replace(/^\s*\/\/.*$/, '').replace(/\s\/\/\s.*$/, '')).join('\n');const begin = code.indexOf('const appWriters = {');@@ -1205,7 +1206,7 @@ test('sdk-build.js reaches the SDK for the app only through appWriters, and eachassert.ok(/\.pushArtifact\(\s*'app'/.test(methodOf('create')) && !/\.pushArtifact\(\s*'app'/.test(outside), 'the SDK\u2019s push of an app is made nowhere else');// The publish phase publishes the app in the envelope of the tables the build has artifacts of, and asks for the request too: a run can reach it without the app step. It adds no form, and applies no Main-form list.// A publish of the app the barrier refuses (an app that holds or adds a form of a withheld table) is reported and the tables are published without it.- assert.ok(/let appWithheld = false;\s*if \(appTarget\) \{\s*try \{\s*await publishTablesBeforeApp\(result\.created\.app\);\s*\} catch \(err\) \{\s*if \(!\(err && err\.code === 'publication-withheld'\)\) throw err;[\s\S]*?\}\s*\}\s*const publishedTargets = await publishTargets\(provision, runner, concurrency, perEntity, appWithheld \? null : appTarget/.test(code), 'the publish phase sends the request before it publishes the app');+ assert.ok(/let appWithheld = false;\s*if \(appTarget\) \{\s*try \{\s*await publishTablesBeforeApp\(result\.created\.app\);\s*\} catch \(err\) \{\s*if \(!\(err && err\.code === 'publication-withheld'\)\) throw err;[\s\S]*?\}\s*\}\s*const publishedTargets = await tablePublication\.sdk\(perEntity, appWithheld \? null : appTarget/.test(code), 'the publish phase sends the request before it publishes the app');// Only the writers that APPLY the spec's Main-form list — the create and the push, which write the spec's app — look its names up. The others (a publish, the placement, the publish phase) apply none, so a name that// went stale on the server is no reason for them to fail, and the placement sends the Main forms of the navigation it pushes, which it reads from the app it fetched.for (const name of ['publish', 'publishPinned', 'placeViews']) assert.ok(!/resolvedMainForms/.test(methodOf(name)), `${name} resolves no Main-form list`);diff --git a/plugins/model-apps/scripts/tests/rename-retry.test.js b/plugins/model-apps/scripts/tests/rename-retry.test.jsnew file mode 100644index 000000000..1760203c8--- /dev/null+++ b/plugins/model-apps/scripts/tests/rename-retry.test.js@@ -0,0 +1,472 @@+'use strict';+// A rename that Windows refuses for a moment (EPERM, EACCES or EBUSY while a scanner, an indexer or a second+// process holds the file) must not stop a build (lib/rename-retry.js). These tests hold the helper to its contract+// and the callers that atomically replace a workspace file to their own messages and codes on a lock that stays.+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { execFileSync } = require('node:child_process');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { renameWithRetry, RENAME_RETRY_BUDGET_MS, PROCESS_WAIT_TOTAL_MS } = require('../lib/rename-retry.js');+const { shortRenameWait, freshRenameWaitTotal } = require('./helpers/short-rename-wait.js');+const { writeFileSafe } = require('../lib/safe-fs.js');+const { openJournal } = require('../lib/build-journal.js');+const records = require('../lib/page-ownership-records.js');+const baseline = require('../lib/deployed-baseline.js');+const store = require('../lib/apply-snapshot-store.js');+const S = require('../lib/apply-snapshot.js');+const { openManagedBindings, CODES } = require('../lib/managed-bindings.js');++const refusal = (code) => Object.assign(new Error(`${code}: resource busy or locked, rename 'a' -> 'b'`), { code, syscall: 'rename', path: 'a', dest: 'b' });+const real = fs.renameSync;++// The tests run as the platform they name: a refusal is waited out on Windows only.+const asPlatform = (t, host) => {+ const platform = Object.getOwnPropertyDescriptor(process, 'platform');+ t.after(() => Object.defineProperty(process, 'platform', platform));+ Object.defineProperty(process, 'platform', { ...platform, value: host });+};+// A short wait for the tests that keep a lock for good: the default is 5 s a rename and 30 s a process.+const shortBudget = (t, ms = 60) => shortRenameWait(t, ms);++// An fs whose rename of a file in `names` (every rename when empty) answers `code` for its first `times` calls+// (all of them when `times` is Infinity), and counts them.+function locked(times, code = 'EPERM', names = null) {+ const state = { renames: 0, refused: 0 };+ const stand = {+ ...fs,+ renameSync: (from, to) => {+ state.renames += 1;+ const mine = !names || names.some((n) => path.basename(String(from)).includes(n) || path.basename(String(to)).includes(n));+ if (mine && state.refused < times) { state.refused += 1; throw refusal(code); }+ return fs.renameSync(from, to);+ },+ };+ return { state, stand };+}++test('on Windows a rename refused with EPERM, EACCES or EBUSY is repeated after growing pauses until it goes through', () => {+ for (const code of ['EPERM', 'EACCES', 'EBUSY']) {+ const calls = [];+ const pauses = [];+ let refused = 0;+ const stand = { renameSync: (from, to) => { calls.push([from, to]); if ((refused += 1) <= 3) throw refusal(code); } };+ renameWithRetry(stand, 'from', 'to', { platform: 'win32', pause: (ms) => pauses.push(ms) });+ assert.equal(calls.length, 4, `${code}: three refusals, then the rename`);+ assert.deepEqual(calls.map((c) => c.join('>')), Array(4).fill('from>to'), 'the same rename each time');+ assert.deepEqual(pauses, [25, 50, 100], `${code}: the pauses grow`);+ }+ const pauses = [];+ renameWithRetry({ renameSync: () => {} }, 'a', 'b', { platform: 'win32', pause: (ms) => pauses.push(ms) });+ assert.deepEqual(pauses, [], 'a rename that goes through the first time never waits');+});++test('a lock that outlasts the per-call budget is the original error, untouched, after pauses that add up to 5 s — and the pauses are capped', (t) => {+ freshRenameWaitTotal(t);+ const original = refusal('EPERM');+ let attempts = 0;+ const pauses = [];+ const stand = { renameSync: () => { attempts += 1; throw original; } };+ assert.throws(() => renameWithRetry(stand, 'a', 'b', { platform: 'win32', budgetMs: 100, pause: (ms) => pauses.push(ms) }), (e) => e === original && e.code === 'EPERM' && e.syscall === 'rename' && e.path === 'a');+ assert.deepEqual(pauses, [25, 50, 25], 'the last pause is cut to what is left');+ assert.equal(attempts, 4);++ const full = [];+ assert.throws(() => renameWithRetry(stand, 'a', 'b', { platform: 'win32', pause: (ms) => full.push(ms) }), (e) => e === original);+ assert.equal(RENAME_RETRY_BUDGET_MS, 5000);+ assert.equal(full.reduce((a, b) => a + b, 0), RENAME_RETRY_BUDGET_MS, 'five seconds in all for one rename');+ assert.ok(Math.max(...full) <= 1000, 'no single pause is longer than a second');+ assert.deepEqual(full.slice(0, 7), [25, 50, 100, 200, 400, 800, 1000]);+ const lower = [];+ assert.throws(() => renameWithRetry(stand, 'a', 'b', { platform: 'win32', budgetMs: 1000, pause: (ms) => lower.push(ms) }), (e) => e === original);+ assert.equal(lower.reduce((a, b) => a + b, 0), 1000, 'a caller may ask for less than the default');+ const over = [];+ assert.throws(() => renameWithRetry(stand, 'a', 'b', { platform: 'win32', budgetMs: 10 * RENAME_RETRY_BUDGET_MS, pause: (ms) => over.push(ms) }), (e) => e === original);+ assert.equal(over.reduce((a, b) => a + b, 0), RENAME_RETRY_BUDGET_MS, 'and never for more');+});++test('a process that has waited out 30 s of locks makes every later refused rename one attempt, as before the retry; a new process starts fresh', (t) => {+ freshRenameWaitTotal(t);+ const original = refusal('EBUSY');+ const stand = { renameSync: () => { throw original; } };+ let spent = 0;+ let calls = 0;+ // Six renames of 5 s each use up the 30 s total exactly: none waits for more than what is left.+ for (; spent < PROCESS_WAIT_TOTAL_MS; calls += 1) {+ const pauses = [];+ assert.throws(() => renameWithRetry(stand, 'a', 'b', { platform: 'win32', pause: (ms) => pauses.push(ms) }), (e) => e === original);+ const waited = pauses.reduce((a, b) => a + b, 0);+ assert.ok(waited > 0 && waited <= RENAME_RETRY_BUDGET_MS);+ spent += waited;+ assert.ok(calls < 20, 'the total must end the waiting');+ }+ assert.equal(PROCESS_WAIT_TOTAL_MS, 30000);+ assert.equal(spent, 30000, 'never more than 30 s in all');+ assert.equal(calls, 6);++ let attempts = 0;+ const pauses = [];+ const counting = { renameSync: () => { attempts += 1; throw original; } };+ assert.throws(() => renameWithRetry(counting, 'a', 'b', { platform: 'win32', pause: (ms) => pauses.push(ms) }), (e) => e === original);+ assert.deepEqual([attempts, pauses], [1, []], 'the next refused rename is ONE attempt');+ // A rename that goes through is unaffected.+ renameWithRetry({ renameSync: () => {} }, 'a', 'b', { platform: 'win32', pause: () => assert.fail('no wait') });++ const script = [+ "const { renameWithRetry } = require(process.argv[1]);",+ "let attempts = 0; const pauses = [];",+ "try { renameWithRetry({ renameSync: () => { attempts += 1; throw Object.assign(new Error('x'), { code: 'EBUSY' }); } }, 'a', 'b', { platform: 'win32', pause: (ms) => pauses.push(ms) }); } catch {}",+ "console.log(JSON.stringify({ attempts, waited: pauses.reduce((a, b) => a + b, 0) }));",+ ].join('\n');+ const fresh = JSON.parse(execFileSync(process.execPath, ['-e', script, path.join(__dirname, '..', 'lib', 'rename-retry.js')], { encoding: 'utf8' }));+ assert.equal(fresh.waited, RENAME_RETRY_BUDGET_MS, 'a new process has its whole budget');+ assert.ok(fresh.attempts > 2);+});++test('the test seam puts the budget and the process total back when its test ends', async (t) => {+ freshRenameWaitTotal(t);+ const original = refusal('EPERM');+ const stand = { renameSync: () => { throw original; } };+ const wait = () => { const pauses = []; assert.throws(() => renameWithRetry(stand, 'a', 'b', { platform: 'win32', pause: (ms) => pauses.push(ms) })); return pauses.reduce((a, b) => a + b, 0); };+ assert.equal(wait(), RENAME_RETRY_BUDGET_MS);+ await t.test('inside', (inner) => {+ shortRenameWait(inner, 60);+ assert.equal(wait(), 60, 'a short budget, from a fresh total');+ });+ assert.equal(wait(), RENAME_RETRY_BUDGET_MS, 'the full budget is back after it');+});++test('any other code, and any other platform, is one attempt exactly as before', () => {+ for (const code of ['ENOENT', 'EXDEV', 'ENOSPC', 'EEXIST', 'EIO']) {+ let attempts = 0;+ const pauses = [];+ const stand = { renameSync: () => { attempts += 1; throw refusal(code); } };+ assert.throws(() => renameWithRetry(stand, 'a', 'b', { platform: 'win32', pause: (ms) => pauses.push(ms) }), { code });+ assert.deepEqual([attempts, pauses], [1, []], `${code} on Windows`);+ }+ for (const host of ['linux', 'darwin']) {+ for (const code of ['EPERM', 'EACCES', 'EBUSY']) {+ let attempts = 0;+ const pauses = [];+ const stand = { renameSync: () => { attempts += 1; throw refusal(code); } };+ assert.throws(() => renameWithRetry(stand, 'a', 'b', { platform: host, pause: (ms) => pauses.push(ms) }), { code });+ assert.deepEqual([attempts, pauses], [1, []], `${code} on ${host}`);+ }+ }+ let attempts = 0;+ assert.throws(() => renameWithRetry({ renameSync: () => { attempts += 1; throw new Error('no code'); } }, 'a', 'b', { platform: 'win32', pause: () => {} }), /no code/);+ assert.equal(attempts, 1, 'an error without a code is not a lock');+});++// safe-fs keeps the short waits it had (25, 50, 100, 200, 400 ms): it writes a maker's files and the build's own diagnostic+// output, which a long synchronous wait would hold up, and a maker can change a file meanwhile. These pin that behaviour.+const BASE_SAFE_FS_WAIT_MS = 25 + 50 + 100 + 200 + 400;+const fakeWaits = (t) => {+ const waits = [];+ t.mock.method(Atomics, 'wait', (_a, _i, _v, ms) => { waits.push(ms); return 'timed-out'; });+ return waits;+};++test('safe-fs writeFileSafe: a replace refused for a moment completes with the new content and no temp; a lock that stays keeps its message after the same short waits', (t) => {+ asPlatform(t, 'win32');+ const waits = fakeWaits(t);+ const dir = makeTempDir('rename-retry-safe-');+ const file = path.join(dir, 'page.tsx');+ fs.writeFileSync(file, 'old');+ const transient = locked(2, 'EBUSY');+ writeFileSafe(file, 'new', { fs: transient.stand });+ assert.equal(transient.state.renames, 3, 'refused twice, then done');+ assert.equal(fs.readFileSync(file, 'utf8'), 'new');+ assert.deepEqual(fs.readdirSync(dir), ['page.tsx'], 'no temp is left');+ assert.deepEqual(waits, [25, 50]);++ waits.length = 0;+ const stays = locked(Infinity, 'EPERM');+ assert.throws(() => writeFileSafe(file, 'never', { fs: stays.stand }), (e) => e.code === 'IO_ERROR' && e.message === `failed to write ${file}: it could not be replaced (EPERM) — another program may have it open. Close it and retry.`);+ assert.deepEqual(waits, [25, 50, 100, 200, 400], 'the same short schedule, no longer');+ assert.equal(stays.state.renames, 6);+ assert.equal(fs.readFileSync(file, 'utf8'), 'new', 'the file is as it was');+ assert.deepEqual(fs.readdirSync(dir), ['page.tsx']);+ const missing = locked(Infinity, 'ENOENT');+ assert.throws(() => writeFileSafe(file, 'never', { fs: missing.stand }), (e) => e.code === 'IO_ERROR');+ assert.equal(missing.state.renames, 1, 'a code that is not a lock: one attempt');+});++test('safe-fs writeFileSafe keeps a maker edit that lands while its replace is refused: the write fails as it always did', (t) => {+ asPlatform(t, 'win32');+ fakeWaits(t);+ const dir = makeTempDir('rename-retry-edit-');+ const file = path.join(dir, 'page.tsx');+ fs.writeFileSync(file, 'old');+ let calls = 0;+ const stand = {+ ...fs,+ renameSync: (from, to) => {+ // The maker saves the file from an editor after the sixth refusal, which is where the short schedule ends.+ if ((calls += 1) <= 6) { if (calls === 6) fs.writeFileSync(file, 'newer maker edit'); throw refusal('EPERM'); }+ return fs.renameSync(from, to);+ },+ };+ assert.throws(() => writeFileSafe(file, 'stale writer bytes', { fs: stand }), (e) => e.code === 'IO_ERROR');+ assert.equal(calls, 6, 'no seventh attempt');+ assert.equal(fs.readFileSync(file, 'utf8'), 'newer maker edit');+});++test('the build journal\'s diagnostic build-status.json waits no longer than before on a permanent refusal', (t) => {+ asPlatform(t, 'win32');+ const waits = fakeWaits(t);+ const dir = makeTempDir('rename-retry-journal-');+ t.mock.method(fs, 'renameSync', (from, to, ...rest) => {+ if (path.basename(String(to)) === 'build-status.json') throw refusal('EPERM');+ return real(from, to, ...rest);+ });+ const j = openJournal(dir);+ for (let i = 0; i < 10; i += 1) j.record({ phase: 'data', label: `step ${i}`, status: 'ok' });+ j.close({ status: 'ok' });+ assert.ok(waits.length > 0, 'the writes did wait');+ assert.ok(Math.max(...waits) <= 400, 'the short schedule');+ assert.equal(waits.reduce((a, b) => a + b, 0) % BASE_SAFE_FS_WAIT_MS, 0, 'a whole short schedule per refused write, as before');+ assert.ok(waits.reduce((a, b) => a + b, 0) <= 12 * BASE_SAFE_FS_WAIT_MS, 'about nine seconds for twelve writes, not twelve minutes');+});++test('a folder where the file is to go is not waited for: its refusal is for good, on Windows as anywhere', () => {+ const dir = makeTempDir('rename-retry-folder-');+ const from = path.join(dir, 'new.tmp');+ const to = path.join(dir, 'record.json');+ fs.writeFileSync(from, 'x');+ fs.mkdirSync(to);+ const original = refusal('EPERM');+ const pauses = [];+ const stand = { ...fs, renameSync: () => { throw original; } };+ assert.throws(() => renameWithRetry(stand, from, to, { platform: 'win32', pause: (ms) => pauses.push(ms) }), (e) => e === original);+ assert.deepEqual(pauses, [], 'no pause');+ // A folder moved to a name nobody has is a lock like any other.+ const moved = [];+ assert.throws(() => renameWithRetry(stand, to, path.join(dir, 'aside'), { platform: 'win32', budgetMs: 50, pause: (ms) => moved.push(ms) }), (e) => e === original);+ assert.deepEqual(moved, [25, 25]);+});++const LIVE = { orgId: 'org-1', envUrl: 'https://e', appUniqueName: 'new_app', appId: 'app-1' };+const eligible = (gen) => { const e = S.makeEnvelope(LIVE, { generation: gen }); S.markEligible(e); return e; };++test('the changed-only snapshot: a write refused for a moment lands whole; a lock that stays throws the original error and keeps the previous snapshot', (t) => {+ asPlatform(t, 'win32');+ const dir = makeTempDir('rename-retry-snap-');+ store.writeSnapshotAtomic(dir, eligible('g1'));+ let refused = 0;+ const flaky = t.mock.method(fs, 'renameSync', (from, to, ...rest) => {+ if (String(from).endsWith('.tmp') && (refused += 1) <= 3) throw refusal(refused === 2 ? 'EBUSY' : 'EPERM');+ return real(from, to, ...rest);+ });+ store.writeSnapshotAtomic(dir, eligible('g2'));+ flaky.mock.restore();+ assert.equal(refused, 4);+ assert.equal(store.readSnapshot(dir).generation, 'g2');+ assert.deepEqual(fs.readdirSync(dir).filter((n) => n.endsWith('.tmp')), []);++ shortBudget(t);+ const original = refusal('EPERM');+ const forever = t.mock.method(fs, 'renameSync', () => { throw original; });+ assert.throws(() => store.writeSnapshotAtomic(dir, eligible('g3')), (e) => e === original);+ forever.mock.restore();+ assert.equal(store.readSnapshot(dir).generation, 'g2', 'the previous snapshot is untouched');+ assert.deepEqual(fs.readdirSync(dir).filter((n) => n.endsWith('.tmp')), [], 'and no temp is left');+});++test('a distrust marker is written after a refusal for a moment; one that cannot be written keeps its { ok: false, reason }', (t) => {+ asPlatform(t, 'win32');+ const dir = makeTempDir('rename-retry-mark-');+ let refused = 0;+ const flaky = t.mock.method(fs, 'renameSync', (from, to, ...rest) => {+ if (String(from).endsWith('.json.tmp') && (refused += 1) <= 2) throw refusal('EPERM');+ return real(from, to, ...rest);+ });+ assert.deepEqual(store.markDistrusted(dir, { reason: 'moved' }), { ok: true });+ flaky.mock.restore();+ assert.equal(refused, 3);+ assert.equal(fs.readdirSync(dir).filter((n) => n.endsWith('.json')).length, 1);++ shortBudget(t);+ const forever = t.mock.method(fs, 'renameSync', () => { throw refusal('EPERM'); });+ const answer = store.markDistrusted(dir, { reason: 'moved' });+ forever.mock.restore();+ assert.equal(answer.ok, false);+ assert.match(answer.reason, /^EPERM: resource busy or locked/);+ assert.deepEqual(fs.readdirSync(dir).filter((n) => n.endsWith('.tmp')), []);+});++test('clearWorkspace makes ONE attempt to move the folder aside: a refusal, for a moment or not, clears nothing and keeps its reason', (t) => {+ asPlatform(t, 'win32');+ const waits = fakeWaits(t);+ const parent = makeTempDir('rename-retry-clear-');+ const target = path.join(parent, 'workspace');+ fs.mkdirSync(target);+ fs.writeFileSync(path.join(target, 'keep.txt'), 'x');+ for (const code of ['EBUSY', 'EPERM', 'EACCES']) {+ let renames = 0;+ const refuse = t.mock.method(fs, 'renameSync', (from, to, ...rest) => { if (from === target) { renames += 1; throw refusal(code); } return real(from, to, ...rest); });+ const held = store.clearWorkspace(target);+ refuse.mock.restore();+ assert.deepEqual(held, { ok: false, reason: `it could not be moved aside (${code})` });+ assert.equal(renames, 1, `${code}: one attempt`);+ assert.ok(fs.existsSync(path.join(target, 'keep.txt')), 'nothing was cleared');+ assert.ok(!fs.existsSync(path.join(target, store.LEASE_FILE)), 'and the lease is released');+ }+ assert.deepEqual(waits, [], 'it did not wait');+ assert.deepEqual(store.clearWorkspace(target), { ok: true });+ assert.deepEqual(fs.readdirSync(parent), []);+});++test('clearWorkspace never deletes a folder that took the place of the one it was asked to clear', (t) => {+ asPlatform(t, 'win32');+ const parent = makeTempDir('rename-retry-replaced-');+ const target = path.join(parent, 'workspace');+ const original = path.join(parent, 'original-moved-by-maker');+ fs.mkdirSync(target);+ fs.writeFileSync(path.join(target, 'original.txt'), 'original cache');+ // A sync client moves the folder and another takes its name while a refused rename is waited out. There is no wait:+ // the one attempt is refused and the answer is { ok: false }.+ t.mock.method(Atomics, 'wait', () => {+ real(target, original);+ fs.mkdirSync(target);+ fs.writeFileSync(path.join(target, 'foreign.txt'), 'new owner content');+ return 'timed-out';+ });+ let first = true;+ t.mock.method(fs, 'renameSync', (from, to, ...rest) => {+ if (from === target && first) { first = false; throw refusal('EPERM'); }+ return real(from, to, ...rest);+ });+ const disposable = (d) => { const r = records.checkPageOwnershipClearable(d); if (!r.ok) throw new Error(r.reason); };+ const result = store.clearWorkspace(target, { beforeRename: () => disposable(target), beforeRemove: disposable });+ // The maker acts right after the refused call.+ if (!fs.existsSync(original)) {+ real(target, original);+ fs.mkdirSync(target);+ fs.writeFileSync(path.join(target, 'foreign.txt'), 'new owner content');+ }+ assert.deepEqual(result, { ok: false, reason: 'it could not be moved aside (EPERM)' });+ assert.ok(fs.existsSync(path.join(target, 'foreign.txt')), 'the replacement folder is intact');+ assert.ok(fs.existsSync(path.join(original, 'original.txt')));+});++test('a teardown that records several page receipts under a lock that stays waits 30 s at most and keeps its fence against a concurrent release', (t) => {+ asPlatform(t, 'win32');+ freshRenameWaitTotal(t);+ const d = makeTempDir('rename-retry-teardown-');+ let now = 1700000000000;+ t.mock.method(Date, 'now', () => now);+ const started = now;+ const mine = store.tombstoneSnapshot(d);+ const other = store.tombstoneSnapshot(d);+ assert.ok(mine.ok && other.ok);+ let beats = 0;+ const timer = setInterval(() => { beats += 1; store.beatTeardown(d, mine.teardownId); }, store.TEARDOWN_BEAT_MS);+ t.after(() => clearInterval(timer));+ let release;+ t.mock.method(Atomics, 'wait', (_a, _i, _v, ms) => {+ now += ms;+ if (!release && now - started > store.TEARDOWN_STALE_MS) {+ // Another process finishes its own teardown once this one has gone five minutes without a beat.+ assert.equal(store.beatTeardown(d, other.teardownId).ok, true);+ release = store.releaseTombstone(d, other.teardownId);+ }+ return 'timed-out';+ });+ const refused = new Map();+ t.mock.method(fs, 'renameSync', (from, to, ...rest) => {+ if (path.basename(String(to)).startsWith('page-ownership.teardown.')) {+ const count = (refused.get(to) || 0) + 1;+ refused.set(to, count);+ if (count < 66) throw refusal('EPERM');+ }+ return real(from, to, ...rest);+ });+ const items = Array.from({ length: 6 }, (_v, i) => ({ key: `page${i}`, name: `Page ${i}`, id: `11111111-1111-4111-8111-${String(i + 1).padStart(12, '0')}` }));+ assert.throws(() => records.recordPageTeardown(d, 'contoso_app', items, 'https://contoso.crm.dynamics.com'));+ assert.ok(now - started <= PROCESS_WAIT_TOTAL_MS, `the writes blocked for ${now - started} ms`);+ if (!release) release = store.releaseTombstone(d, other.teardownId);+ assert.equal(release.deleted, false, 'another teardown must not delete the fence of one that is still running');+ assert.equal(release.left, true);+ assert.ok(fs.existsSync(store.snapshotPath(d)), 'the snapshot is still there');+});++test('the managed binding store: a write refused for a moment is committed; a lock that stays is still managed-binding-write-failed and the file is as it was', (t) => {+ asPlatform(t, 'win32');+ const dir = makeTempDir('rename-retry-mb-');+ const open = ({ dir: where = dir } = {}) => openManagedBindings({ workspaceDir: where, environment: 'https://contoso.crm.dynamics.com', appUniqueName: 'contoso_app', solutionUniqueName: 'contoso_solution' });+ const attempt = (s) => s.prepareAttempt({+ family: 'form', key: 'account/main', baseGeneration: null, root: { kind: 'form', key: 'account/main', id: '11111111-1111-4111-8111-111111111111' },+ knownScopes: [{ type: 'table', table: 'account' }], declarationSha256: 'e'.repeat(64), publication: { scope: { type: 'table', table: 'account' }, state: 'owed' },+ });+ let refused = 0;+ const flaky = t.mock.method(fs, 'renameSync', (from, to, ...rest) => {+ if (String(from).endsWith('.tmp') && (refused += 1) <= 2) throw refusal('EBUSY');+ return real(from, to, ...rest);+ });+ const first = open();+ assert.ok(attempt(first), 'the attempt is recorded');+ flaky.mock.restore();+ assert.equal(refused, 3);+ const before = fs.readFileSync(first.file, 'utf8');++ shortBudget(t);+ const forever = t.mock.method(fs, 'renameSync', (from, to, ...rest) => { if (String(from).endsWith('.tmp')) throw refusal('EPERM'); return real(from, to, ...rest); });+ let thrown = null;+ try { attempt(open({ dir: makeTempDir('rename-retry-mb-lock-') })); } catch (e) { thrown = e; }+ forever.mock.restore();+ assert.equal(thrown && thrown.code, CODES.writeFailed);+ assert.match(thrown.message, /could not be written \(EPERM\)/);+ assert.equal(fs.readFileSync(first.file, 'utf8'), before, 'the first store is as it was');+});++// The download writes the deployed baseline WITHOUT the build lease, so it renames once: a write that was refused and+// retried could land after a newer build's write and put the older baseline back.+test('the deployed baseline: an older unleased write that is refused once does not replace the newer baseline a build wrote meanwhile', (t) => {+ asPlatform(t, 'win32');+ const dir = makeTempDir('rename-retry-baseline-');+ const identity = { environment: 'https://contoso.crm.dynamics.com', appUniqueName: 'contoso_app' };+ const spec = (name) => ({+ solution: { uniqueName: 'contoso_solution', publisherPrefix: 'contoso' },+ app: { name, uniqueName: 'contoso_app' }, pages: [],+ appShell: { areas: [{ groups: [{ subAreas: [{ entity: 'account', title: name }] }] }] },+ });+ baseline.writeBaseline(dir, spec('Initial'), identity);+ const waits = fakeWaits(t);+ let refused = false;+ let calls = 0;+ let newer = false;+ t.mock.method(fs, 'renameSync', (from, to, ...rest) => {+ if (to === baseline.baselinePath(dir)) {+ calls += 1;+ if (!refused) { refused = true; throw refusal('EPERM'); }+ }+ return real(from, to, ...rest);+ });+ const buildFinishes = () => { newer = true; baseline.writeBaseline(dir, spec('Newer completed build'), identity); };+ // The build (under its lease) finishes at whatever moment the download waits, or right after it returns.+ t.mock.method(Atomics, 'wait', (_a, _i, _v, ms) => { waits.push(ms); if (!newer) buildFinishes(); return 'timed-out'; });+ let caught = null;+ try { baseline.writeBaseline(dir, spec('Older download'), { ...identity, fromSpec: true }); } catch (e) { caught = e; }+ if (!newer) buildFinishes();+ assert.equal(caught && caught.code, 'EPERM', 'the refused write fails with its original error, as before');+ assert.equal(calls, 2, 'one attempt for the download, and the build\'s own write');+ assert.deepEqual(waits, [], 'it did not wait');+ assert.equal(baseline.readBaseline(dir, identity).app.name, 'Newer completed build');+});++test('the retried state files still retry: the snapshot, the managed binding store and the distrust marker are covered above, and a write that opts out is the only single attempt', (t) => {+ asPlatform(t, 'win32');+ const dir = makeTempDir('rename-retry-optout-');+ const file = path.join(dir, 'record.json');+ for (const [opts, renames] of [[undefined, 3], [{ retryLock: true }, 3], [{ retryLock: false }, 1]]) {+ let calls = 0;+ const flaky = t.mock.method(fs, 'renameSync', (from, to, ...rest) => { calls += 1; if (calls <= 2) throw refusal('EBUSY'); return real(from, to, ...rest); });+ const run = () => store.writeFileAtomic(file, 'text', opts);+ if (renames === 1) assert.throws(run, { code: 'EBUSY' }); else run();+ flaky.mock.restore();+ assert.equal(calls, renames);+ assert.deepEqual(fs.readdirSync(dir).filter((n) => n.endsWith('.tmp')), [], 'no temp is left');+ }+});diff --git a/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js b/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.jsindex 5ffeecc62..3af9d299d 100644--- a/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js@@ -22,6 +22,7 @@ const { writeBaseline, readBaseline } = require('../lib/deployed-baseline.js');const { sha256 } = require('../lib/hash.js');const { readPageOwnership, readPendingCreations, recordPagePending, recordPageCreation } = require('../lib/page-ownership-records.js');const { currentReadSdk } = require('./helpers/app-membership-sdk.js');+const { shortRenameWait } = require('./helpers/short-rename-wait.js');const { OBJECT_DIVISION_PAGE, MISREAD_PAGES, HIDDEN_CALL_PAGE, PREFIX_INCREMENT_PAGE, TEMPLATE_LINE_PAGE, JSX_TEXT_PAGE, ELEMENT_AFTER_OPERATOR_PAGES, ELEMENT_LOOKALIKE_PAGES, ELEMENT_PAGE_TOKEN_LINE, FUNCTION_TYPE_PAGES } = require('./helpers/misread-page.js');const { withPageType, PAGE_TYPE } = require('./helpers/page-component-type.js');// What a guess costs a page where the TypeScript parser does not settle it (lib/typescript-views.js): these tests read the page with the lexer alone.@@ -4418,7 +4419,8 @@ test('deploy: a local page record that cannot be read stops the build once, in a} finally { fs.rmSync(appDir, { recursive: true, force: true }); }});-test('deploy: a creation receipt that cannot be saved stops the build once, in a folder called "SQL Timeout Workspace" — the page exists, and running the earlier phases again would not save the receipt', async () => {+test('deploy: a creation receipt that cannot be saved stops the build once, in a folder called "SQL Timeout Workspace" — the page exists, and running the earlier phases again would not save the receipt', async (t) => {+ shortRenameWait(t);const { appDir, spec } = onePageApp('Overview');const workspaceDir = path.join(appDir, 'SQL Timeout Workspace');try {diff --git a/plugins/model-apps/scripts/verify-model-app.js b/plugins/model-apps/scripts/verify-model-app.jsindex 1a7e43637..80cc1915d 100644--- a/plugins/model-apps/scripts/verify-model-app.js+++ b/plugins/model-apps/scripts/verify-model-app.js@@ -74,6 +74,8 @@ const { sameFormXmlAcrossLayers } = require('./lib/formxml-layers.js');// The app's id and the ids of the roles associated with it live in lib/app-roles.js: the design document reads the same relationship. Still exported from here.const { appIdFor, appRoleIdsFor } = require('./lib/app-roles.js');const { makeWritesBlocking } = require('./lib/output-redaction.js');+const { createCommandStateTransport } = require('./lib/command-state-transport.js');+const { verifyCommandStates } = require('./lib/command-state-read.js');const { uniqueKeys } = require('./lib/unique-keys.js');// An SDK on a THROWAWAY workspace — a temporary folder `dispose()` removes — and never on the app folder's own.@@ -185,6 +187,8 @@ function singleFlightFirstReads(sdk) {function readerFor(sdk, appUnique, opts) {opts = opts || {};+ // The command rows are read with the run's raw client (opts.commandStateClient) at the SDK's own api root, as list-command-states.js reads them.+ const commandStateRoot = sdk && sdk.dataverse && typeof sdk.dataverse.apiUrl === 'function' ? (path) => sdk.dataverse.apiUrl(path) : null;sdk = singleFlightFirstReads(sdk);// The page backend (lib/genpage-sdk.js): the environment's pages and one page's source. It reads by page id, so no app id is needed.const genpage = opts.genpage;@@ -295,6 +299,11 @@ function readerFor(sdk, appUnique, opts) {// the build makes before it reuses one — or null when there is none:// GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_/scripts/form.js'&$top=1// { "value": [ { "webresourceid": "…", "content": "dmFyIEZvcm0gPSB7…" } ] }+ // commandStates(spec): each declared commandStates[] entry checked against its row's stored flags (lib/command-state-read.js). Only when+ // the run gave its raw client: without one the capability is absent and verify fails every declared entry rather than pass it.+ ...(opts.commandStateClient && commandStateRoot ? {+ commandStates: async (spec) => verifyCommandStates(createCommandStateTransport({ client: opts.commandStateClient, apiUrl: commandStateRoot }), spec),+ } : {}),webResource: async (name) => {const rows = await sdk.queryRecords('webresource', { select: ['webresourceid', 'content'], filter: `name eq '${odataLit(name)}'`, top: 1 });const row = rows && rows[0];@@ -864,7 +873,7 @@ async function main() {? readVerifyManifest({ workspaceDir, environment: dataverseOrigin(env), appUniqueName: appUniqueName(spec), solutionUniqueName: spec.solution.uniqueName }): undefined;// `appDir`: a web resource's `contentPath` is read relative to the spec's folder, as the build reads it, to compare its content.- r = await verifySpec(spec, readerFor(session.sdk, appUniqueName(spec), { genpage, workspaceDir, isolatedReader: isolatedReaderFor(env, { httpClient }) }), { baselineSpec, languageCode, appDir: path.dirname(specPath), managedManifest });+ r = await verifySpec(spec, readerFor(session.sdk, appUniqueName(spec), { genpage, workspaceDir, commandStateClient: httpClient, isolatedReader: isolatedReaderFor(env, { httpClient }) }), { baselineSpec, languageCode, appDir: path.dirname(specPath), managedManifest });// Only when asked, and before the SDK's workspace is disposed below.if (flags['inspect-components'] === true) components = await inspectComponents(session.sdk, spec);} finally {diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.mdindex f7fcb798a..35cffa8df 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -64,7 +64,8 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfaces`100000003`, because they are assigned per publisher. Resolve by label via `getOptions()`(see `references/app-spec-schema-advanced.md` → webResources). Note also that command and web-resource**edits do not redeploy on rebuild** — the phases reuse what exists, so changing a button or a- script means deleting it first (the build warns, and verify fails, when a web resource's deployed+ script means deleting it first (only a button's hidden / disabled state can be set in place, with+ `commandStates[]` below; the build warns, and verify fails, when a web resource's deployedcontent differs from the spec's). This does not apply to recovery of the build's own`WEB_RESOURCE_UNVERIFIED` row: keep that row and the same build workspace, then follow its halt.When the maker wants a rebuild to keep a web resource's content in step with the spec, mark that@@ -73,6 +74,23 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfacesolder spec. A rebuild that would change one that exists stops before writing and names its approval(`--authorize adopt:webresource:<web resource name>`) with the components that depend on it: show them to themaker and let them choose. Emptying its content also needs `--allow-destructive`; the halt says so.+- **Show or hide an existing button** — `commandStates[]` (`minimumPluginVersion: "2.24.0"`, `app.uniqueName`):+ only when the maker asks to show, hide, enable or disable a modern button that already exists. **Never invent a+ row id**: run `node scripts/list-command-states.js --env <envUrl> --app <uniqueName>` and pick the row by `rowId`+ (never by caption) among `candidate: true` rows; write `scope: "table"` only (app-scoped buttons are refused in+ this version) and only `hidden` / `disabled` — a normal empty `visibilitytype` on a button `commands[]` built is+ static and is never a reason to change it. Never write a command `key` in the same spec, and never create a+ button with `commands[]` and set its state in the same build: create it in one build, add the state in the next.+ The apply is a full build with `--publish`. Run a dry run first and show the maker every+ `--authorize overwrite:command-state:…` (one per row change) and `--authorize publish:command-state-table:…`+ token it prints — the table one publishes **all** saved customizations on that table, for every app that shows it —+ and pass them exactly as printed. Never replay a row write by hand: on `command-state-write-unknown` or+ `command-state-version-conflict`, list the row again, dry-run again and get the new approval (an ordinary phase+ retry of the build re-plans from a fresh read). Report three things separately: the rows saved, the table+ publication confirmed — or `command-state-publish-unconfirmed` ("saved, not published") — and what the maker sees+ in the app, which neither the build nor `--verify` (stored flags only) checks. A table publish that was sent can+ still complete after a halt or after the entry is removed; this release keeps no record of it across runs, and a+ later publishing run requests the table again only because the spec still names it.- **Form logic without code** — `businessRules[]`: show/hide, lock/unlock, set-required andset-value, driven by a condition on the record. **Reach for a business rule before form JS** whenthe requirement is field-level and declarative — it is visible in the maker, survives solution@@ -958,7 +976,8 @@ 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**).+ **Declared form layouts**). `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 issafe; they just aren't editable through the downloaded spec. Change them in Maker or a fresh spec.The download names every one it leaves out — the command-bar buttons of the app's tables included —