Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

model-apps 2.23.0: retry-stable configuration identities (opt-in) (#823)

Akshay Maloo9d26fde082b4
diff --git a/.github/workflows/model-apps-script-tests.yml b/.github/workflows/model-apps-script-tests.yml
index da6f3cf4a..aa9232995 100644
--- a/.github/workflows/model-apps-script-tests.yml
+++ b/.github/workflows/model-apps-script-tests.yml
@@ -66,9 +66,10 @@ jobs:
test-model-apps-scripts:
name: test-model-apps-scripts (${{ matrix.os }}, node ${{ matrix.node }})
runs-on: ${{ matrix.os }}
- # The suite takes about a minute on every runner. A test that hangs (a child process waiting on
- # stdin, say) would otherwise hold the job for the six-hour default.
- timeout-minutes: 20
+ # The suite takes 8-15 minutes on Linux and macOS and up to about 20 on Windows, where Node 20 is the
+ # slowest and has been cancelled at a 20-minute limit while passing. A test that hangs (a child
+ # process waiting on stdin, say) would otherwise hold the job for the six-hour default.
+ timeout-minutes: 30
# Defense-in-depth: opt this CI job out of telemetry transmission so a test
# that forgets to isolate emission can never POST to a real collector. The
# plugin's committed ikey.json ships live (`disabled: false`) with real
diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.json
index 8b382e514..6ed55e112 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.22.0",
+ "version": "2.23.0",
"description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.json
index 8b382e514..6ed55e112 100644
--- a/plugins/model-apps/.plugin/plugin.json
+++ b/plugins/model-apps/.plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "model-apps",
- "version": "2.22.0",
+ "version": "2.23.0",
"description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.md
index f83349ea7..c18665f1d 100644
--- a/plugins/model-apps/AGENTS.md
+++ b/plugins/model-apps/AGENTS.md
@@ -153,7 +153,7 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
- **`scripts/lint-app-spec.js`** — the CLI surface for both gates, for a headless author or a CI
job (#560). Runs `migrateAppSpec` → `validateAppSpec` (what the build runs on load) → `lintAppSpec`
(guardrails the builder does **not** run), and exits non-zero on errors (`--strict` also fails on
- warnings, including the one for an unknown key on a `views[]` entry or its filters). Prefer it over calling the library through `node -e`: linting the file **as written**
+ warnings). An unknown key on a `views[]` entry or its filters is an error (#827), not a warning. Prefer it over calling the library through `node -e`: linting the file **as written**
rather than the migrated shape is what let a spec pass the lint and then fail the build (#545).
`--profile` defaults to **`plan`**, not `deploy`, because the authoring flow runs this while pages
are still intents — a deploy default rejects a normal work-in-progress spec. `plan` relaxes only
@@ -2068,10 +2068,10 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
dropped and counted in `droppedSubareas`.
- **`scripts/verify-model-app.js` → `scripts/lib/verify-spec.js`** — read-only reconcile of the App Spec
against what actually deployed; exits non-zero and lists anything missing, catching silent partial
- builds. It validates the spec first under the `deploy` profile, with five compatibility downgrades
- (`relationshipCollisions: 'warn'`, `columnValues: 'warn'`, `fieldOptionKeys: 'warn'`, `primaryAttributeKeys: 'warn'` and `declaredKeyCollisions: 'warn'`): a spec an earlier release accepted and built — a 1:N and an N:N
+ builds. It validates the spec first under the `deploy` profile, with six compatibility downgrades
+ (`relationshipCollisions: 'warn'`, `columnValues: 'warn'`, `fieldOptionKeys: 'warn'`, `primaryAttributeKeys: 'warn'`, `viewKeys: 'warn'` and `declaredKeyCollisions: 'warn'`): a spec an earlier release accepted and built — a 1:N and an N:N
that share a schema name, an AutoNumber column with no format, a `required` that is not `true`, `false` or `"recommended"`, a key a form's
- `fieldOptions` entry does not take, a key a table's `primaryAttribute` does not take, two declared views (or two declared charts) with one name on one table — is verified, with a warning that names the fix, and is never refused before anything is read (the
+ `fieldOptions` entry does not take, a key a table's `primaryAttribute` does not take, a key a `views[]` entry or one of its filters does not take, two declared views (or two declared charts) with one name on one table — is verified, with a warning that names the fix, and is never refused before anything is read (the
build, the lint and the provisioning gate keep these as errors). **Every `WARNING:` line it prints on stderr — those findings, the spec's other warnings, and a page
workspace it could not remove — is also in the result JSON's optional `warnings` array** (the same messages, without the prefix, in the order
printed; left out when there is none, as `unverified` is), so a caller that reads only the JSON loses none of them. It is there on a failed
@@ -3310,6 +3310,101 @@ retired, so they have no incarnation. Tests: `tests/managed-bindings.test.js` ("
`tests/creates-composite-catalog.test.js` ("incarnations"), and "declared again after" / "after
retirement" / "two retirements" in `tests/sdk-build-declared-{forms,dashboards,rules,bpf}.test.js`.
+**Protected configuration** (`configurationIdentity: "stable-v1"`, `minimumPluginVersion: "2.23.0"`, a lint
+warning below it). Declared environment variables, connection references, Custom APIs (with their children)
+and duplicate rules (with their conditions) get exact ids (`lib/configuration-create-bindings.js` plans,
+observes and classifies them) and are bound in the managed binding store. `lib/configuration-protected.js`
+is the one hookup: `createProtectedConfiguration({ store, gate, ctx, apiBase })` answers `preflight` (the
+whole-plan, read-only check `configuration-build.js` runs before the build's first service change, the
+solution version included) and `port` (the exact-id port `configuration-artifacts.js` uses through
+`exactPortOf` instead of the managed-artifacts manifest and the adoption policy). Without a hookup the
+opt-in stops before any request (`create-identity-unverified`). The build command supplies it: `runBuildCommand`
+(`build-model-app.js`) makes the deferred managed create gate (`managed-create-transport.js`) only for an apply where
+protected configuration is in play (`sdk-build.js` `protectedConfigurationInPlay`: the opt-in is set, or the
+workspace's binding store holds configuration row state — a local file read that sends nothing; a store it cannot
+read counts as in play, so the preflight stops on it), and installs it on the one HTTP client (`makeSdk`,
+`composeWriteGates` with the workflow effect gate). `runSdkBuildPhases` binds it to the store and builds the hookup
+over it (`protectedConfigurationFor`, `apiBase` `<env>/api/data/v9.0`) before any service change, whatever
+`--stage`/`--phase` selects. While the gate exists `--changed-only` takes no shortcut: `runBuildCommand` runs the
+full build instead of `changed-only-flow.js` (which forces `full` too when handed the gate,
+`PROTECTED_CONFIGURATION_FULL`), because the apply snapshot a no-op or pages-only apply trusts does not describe the
+configuration rows (a deleted bound row, an unreadable store or a refused edit leave it as it was). Any other partial
+range on `--apply` is refused before anything is sent (`buildModelApp`), so no early exit reports success over a
+pending obligation. Otherwise no gate is made and no protected module is loaded, so a build without protected
+configuration sends, prints and loads what it did before, with one deliberate change: the configuration fields are now
+in `phase-diff.js`'s `data-model` slice, so a `--changed-only` apply whose only change is one of them runs the full
+build instead of reporting nothing to do (an unchanged spec is still the no-op). The whole-build
+retry runs the same command again over the same store, so it finds the rows at the ids the first attempt
+bound (a lost or uncertain create stops as `create-outcome-unknown`, never retried). The `adopt:` approvals a
+stop prints are read by `configurationAuthorizationKeys` (`adopt:<kind>:<port key>`,
+`adopt:<child kind>:<encoded port key>/<encoded slot>`; only under the opt-in, the root and child declared) into
+`opts.configurationApprovals`; a root's approval never covers its children. The build's configuration items
+work in a throwaway SDK workspace per command run (`makeSdk`), so a kept local copy lasts until that run ends.
+Edits: a duplicate rule is created with its conditions, completes its initial
+publication/state, and is then only verified (any later field, condition or state change, the
+`CompoundUpdateDuplicateDetectionRule` shapes and an `If-Match: *` field PATCH included, is
+`configuration-edit-unsupported`); a Custom API takes one request alone (the root, one child create or
+one child's labels), the root PATCH with new children, or two or more new children only, each with the
+row's exact `If-Match` (a multi-request edit goes through one checked `$batch` change set, classified part
+by part); one child removal is `configuration-protected-removal-unsupported`, anything else
+`configuration-edit-unsupported`. A pending create is decided from its own persisted expectation
+(`recoverPending` over `managed-create-context.js` `classify`): complete -> settled; proved unsent ->
+resumed under the same ids; otherwise `create-completion-required`, `create-ownership-required` (with each
+row's exact `adopt:` token in the message) or `managed-pending-intent-changed`. The original plan's rule
+state stays owed and an uncertain, failed or lost publish is never sent again; a bound rule is never published.
+The one exception (`unsentPublication`, `publishOnce`): a saved rule create (`acknowledgedRoot`) read
+unpublished whose `rule-state` effect is still `dispatched: false`, and which would commit (or need only
+ownership approvals, named first) if that publish had landed, sends `PublishDuplicateRule` once under a new
+epoch (`store.claimUnsentRowEffect`, through `ctx.claimEffect`), sealed dispatched before it leaves, then
+reads the rule a bounded number of times and settles. A pending EDIT is decided by
+the rows its attempt persisted (`settlePendingEdit`, answering `settled`, `retired` or `needs-write`): complete
+-> committed read-only; already at its target -> accepted read-only only when that acceptance commits (its
+verdict is judged in the preflight by `judgeReadOnly` and again by `resolve`, so an ownership approval it needs
+or a membership removed by hand stops the build, never a no-op success); proved unsent with the
+same rows and a target not there yet -> resumed under its token, ids, parents and generation (`resolve` answers
+`owed`, so `planOne` never plans it `unchanged` and its membership is added only inside its attempt); rows
+changed -> retired while prepared,
+otherwise `create-identity-conflict`. A create or edit whose push the run did not check is released by that
+same run when its record proves nothing left (`ctx.release` -> `store.retireProvenUnsentAttempt`: at the
+run's own epoch, `attemptProvenUnsent`, the group still at the attempt's base generation, no effect a read
+found made): an operation the SDK refused before its first request (`CUSTOM_API_LABELS_UNSUPPORTED` on an
+environment with more than one language) must not hold the group, or every later declaration — the earlier
+one, another edit, the same one — stops on a pending attempt prepared for another declaration. Anything that
+may have been sent keeps the attempt, and the run's own stop stands either way. Environment variable and connection reference updates (definition, first
+value, own value replacement) go through the protected port as one checked set over the item's plan; a value
+row the binding does not hold is `create-identity-conflict`. Before any service change, every build runs the
+store-driven `pendingSweep` (the hookup's `sweep`, run by `configuration-build.js` `sweepPendingConfiguration`
+regardless of the opt-in, the declarations or the phases): an undeclared pending or unusable protected record
+stops it with `managed-settlement-pending`. Before an overwriting fetch of a protected item (preflight, port and
+verify), a workspace copy with unsynced edits (`hasUnsyncedEdits`) stops it. The build never resets or deletes
+that copy on its own, a failed or uncertain send included: the copy is shared with the maker, the SDK diff is not
+locked and there is no conditional overwrite, so no check can prove a reset discards only the build's own change
+(a maker edit made while the build prepares its push, or just after any comparison, would be lost). After such a
+send the copy is kept as it is and the pending attempt is still recovered read-only from what it persisted. The
+next build's preflight stops on the copy before any write with `workspace-copy-unsent-edits` (the declared views'
+and charts' code, `sdk-build.js` `refuseUnsentCopy`) and prints the one approval that replaces it,
+`--authorize overwrite:<kind>:<key>` (`overwriteKey`: the configuration kind and the port key — a name in lower
+case, a rule's key exactly; read by `configurationAuthorizationKeys` into `opts.authorizedOverwrite`, only under
+the opt-in). Under that approval only, `replaceLocalCopy` reads the service row exactly: present -> overwrite
+fetch; absent (a create never taken) -> local delete; a denied or failed read or any other answer keeps the copy
+and stops. Only a collection holding the exact key approves (`approvesOverwrite`): the shared `isAuthorized`'s
+blanket `true` approves nothing here. The key names the item, not a revision: it replaces the copy as it is when
+the approved build runs, edits made after the stop was printed included (the views' and charts' contract).
+Nothing else discards it; the port's and verify's own exact reads (`refuseLocalDraft`) stop on it too
+(`create-completion-required`). A bound environment variable's value clear (a settings
+`Value` of `null`, a DELETE of its value row) is refused in the preflight with
+`configuration-protected-removal-unsupported`, authorized or not. Without the opt-in, `preflight` asks the
+hookup the build hands over (`opts.protectedConfiguration.obligations`, `optInObligations`, a local store read
+only): a declared item the store holds, committed or pending, stops with `create-identity-opt-in-required`.
+`configuration-build.js` never requires `configuration-protected.js` itself, and verify requires it only under
+the opt-in (a gated edge in `tests/creates-port.test.js`). Verify
+(`verify-model-app.js` `readerFor`, shared with the build's `--verify`) passes `protectedVerifyPort` over the
+workspace's `managedManifestView` as an exact port: `verifyKind` reads each protected item at its bound id
+(`locateExactly`) and reports the typed code (`configuration-row-not-found`, `create-identity-unverified`;
+`managed-settlement-pending` is unverified), never a name lookup. Tests: `tests/configuration-protected.test.js`,
+`tests/configuration-create-bindings.test.js`, and through the build command with the real bundle (derived ids,
+a lost create and its approvals, the whole-build retry, field approvals, the stops that send nothing, and a
+default build that loads no protected module) in `tests/configuration-build-real-bundle.test.js`.
**Stable create ids** (`createIdentity: "stable-v1"`, `minimumPluginVersion: "2.21.0"`; new apps only).
The only place the engine reads the field is one gated `require` of `lib/creates-stable-build.js` in
`lib/sdk-build.js` (pinned by `creates-port.test.js`: a spec without it loads none of the stable modules
diff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.md
index fd3ec7657..57aa0fda5 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.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).
+- **Before its first write, whatever `--stage` or `--changed-only` selects,** a build checks every protected item; a lost create is bound only after each printed `--authorize adopt:` token (a root's approval never covers its children).
+- **Protected rows** are verified by id. A namesake at another id halts `create-identity-conflict`; deletes and value clears halt `configuration-protected-removal-unsupported`; removing the opt-in while rows are bound halts `create-identity-opt-in-required`.
+- **Custom APIs (opt-in):** a root-field edit with new request parameters or response properties is sent as one checked change set; other multi-part edits halt `configuration-edit-unsupported`.
+- **Duplicate-detection rules (opt-in)** are published once, then only verified; later edits halt `configuration-edit-unsupported`. A first publication that may have been sent is never resent; if a read cannot show it published, publish the rule by hand (#808).
+- **`--changed-only`** now applies a spec whose only change is a configuration item instead of reporting nothing to apply. Builds without the opt-in are otherwise unchanged, apart from the view check below.
+- **Views:** a view or view filter with an unknown key (for example `filter` instead of `filters`) is refused, naming the key to write, instead of being built without it; the inert `type` key stays allowed. Teardown accepts such a spec; verify warns (#827).
+
+### Limits
+
+- Rows created before opting in are not migrated (#807 stays open). Make later duplicate-rule edits outside the plugin. Keyed command bars (show or hide buttons on rebuild) are not in this release (#812).
+
## [2.22.0]
- **Teardown:** a table's only Main form, refused with `0x8004F661`, settles with its table: one run removes the solution (#806).
diff --git a/plugins/model-apps/references/app-spec-schema-advanced.md b/plugins/model-apps/references/app-spec-schema-advanced.md
index a93513424..066a3debc 100644
--- a/plugins/model-apps/references/app-spec-schema-advanced.md
+++ b/plugins/model-apps/references/app-spec-schema-advanced.md
@@ -1218,4 +1218,157 @@ downloaded spec. The only value is `"stable-v1"`; any other value is a validatio
A page edit makes that check under the app's build and pages leases, so it is refused with
`build-locked` while a build of the app runs in the same workspace; run it again once the build ends.
- **`--verify`** reads each bound view or chart by its id. A binding whose create is not yet settled, or
- a file it cannot read, is reported as unverified, never as a pass.
\ No newline at end of file
+ a file it cannot read, is reported as unverified, never as a pass.
+
+## configurationIdentity (optional — exact ids for protected configuration)
+
+Set `minimumPluginVersion: "2.23.0"` with it (a lower or missing floor is a lint warning: older plugins
+ignore the field, keep no binding store for configuration and find these items by name). The only value
+is `"stable-v1"`; any other value is a validation error (`create-identity-invalid`), and a spec without
+the field builds exactly as before.
+
+```jsonc
+{ "minimumPluginVersion": "2.23.0", "configurationIdentity": "stable-v1",
+ "environmentVariables": [ /* … */ ], "connectionReferences": [ /* … */ ],
+ "customApis": [ /* … */ ], "duplicateDetectionRules": [ /* … */ ] }
+```
+
+- **What it covers.** The declared environment variables, connection references, Custom APIs (with
+ their request parameters and response properties) and duplicate detection rules (with their
+ conditions). Each is created at an id the spec fixes and recorded in the build's binding store
+ (`managed-bindings.<hash>.json`, the same file as `createIdentity`; keep it with the build workspace).
+ A later build finds each row by that id, never by name: a bound row deleted outside the plugin stops
+ the build with `configuration-row-not-found` and is never replaced by a namesake.
+- **The binding store comes from the build.** Under the field, a build that cannot open the binding
+ store for configuration stops before any request is sent (`create-identity-unverified`).
+- **Opting in does not migrate an existing app.** Setting `configurationIdentity: "stable-v1"` does not
+ migrate an existing app. A namesake created earlier at another id stops the first protected create
+ with `create-identity-conflict`, even if it is the only match; nothing is created or bound, and no
+ approval token selects a namesake. Keep the app without the field, or move it to the reserved ids
+ outside the plugin. An app that already has protected bindings cannot go back: see "Removing the
+ field" below.
+- **An uncertain lookup is not absence.** If the namesake lookup a first create needs cannot be read
+ completely (a failed read, a page that cannot be continued), the build stops with
+ `create-identity-unverified` and creates or binds nothing for that item. Restore access or reliable
+ reads and build again.
+- **No deletion.** Under the field, clearing an environment variable's value (a deployment-settings
+ `Value` of `null`, which deletes its value row), removing a Custom API child, or an unexpected delete
+ in a protected change stops with `configuration-protected-removal-unsupported` before anything is sent, authorized or not
+ (a removed duplicate-rule condition is a rule edit: `configuration-edit-unsupported`). Make the
+ change outside the plugin, with the maker portal or the Web API. Supported changes keep their
+ `--authorize` tokens, and builds without the field are unchanged. Deleting a bound row outside the
+ plugin does not release its binding: the next build stops with `configuration-row-not-found`. Never
+ delete or reset the binding store to clear a stop.
+- **Removing the field.** Removing `configurationIdentity` from an App Spec whose binding store still
+ holds a declared protected item (bound, or a create still being settled) stops the build before any
+ request with `create-identity-opt-in-required`: those items would otherwise be found by name again,
+ where a namesake could stand in for the bound row. Put the field back.
+- **Verify reads the bound ids.** Under the field, `verify-model-app` checks each declared protected
+ item at the id its binding holds, read-only, never by name: a bound row that is gone fails with
+ `configuration-row-not-found` even when a namesake exists, an item with no binding (or no readable
+ binding store) fails with `create-identity-unverified`, and an item whose create is still being
+ settled is reported unverified. Keep the build workspace with the binding store where verify runs.
+- **Checked before anything is sent.** Every declared protected item is read and judged before the
+ build's first service change, the solution version included: a first create's reserved id and its
+ namesake lookup too, so a create that would stop with `create-identity-conflict` or
+ `create-identity-unverified` stops the whole build with nothing sent. An edit the plugin does not
+ make stops the whole build there, with nothing sent (`configuration-edit-unsupported`).
+- **Duplicate rules: create only.** A protected duplicate rule is created with its conditions, completes
+ its initial publication/state, and is then only verified; later edits are outside the plugin. A
+ later change of its fields, conditions or state stops with: "This protected duplicate rule can be
+ created with its conditions and initial state, then verified. Later field, condition or state edits
+ are not supported. No service changes were sent by this build. Make this edit outside the plugin,
+ keeping the binding store and exact ids." A rule unpublished outside the plugin is not published
+ again: the build stops.
+- **Custom APIs.**
+
+ | Change to a bound Custom API | Result |
+ |---|---|
+ | One request on its own: the root's editable fields, one new child, or one child's labels | made |
+ | The root's editable fields together with one or more new children | made, as one change set |
+ | Two or more new children, nothing else | made, as one change set |
+ | Removing one child | stops: `configuration-protected-removal-unsupported` |
+ | Anything else (two label edits, labels with any other change, a removal with any other change, a child's fixed field) | stops: `configuration-edit-unsupported` |
+
+ The refusal reads: "This protected Custom API change is not a supported single request or create-only
+ changeset. No service changes were sent by this build. Separate supported non-removing single-request
+ edits across builds, or make the change outside the plugin. Removals require maintenance outside the
+ plugin." Every write names the row's exact id and its current version (`If-Match`). A change of
+ `isPrivate` still needs `--authorize`. An implementation registered outside the plugin (the API's
+ plug-in type) is kept: no write sends it, and an edit is complete only while the row still holds the
+ implementation it was planned over. One replaced or removed while the edit is written leaves the edit
+ unfinished with `create-identity-conflict`, and the next build sends nothing for it.
+- **Environment variables and connection references** are edited at their exact ids, each as one
+ checked change over the item's whole plan: a definition edit, the first value (created at the id the
+ spec fixes, then bound) or a new value for its own value row. A value row under a bound definition
+ that the binding does not hold is never overwritten or adopted, whatever `--authorize` tokens are
+ given: the build stops with `create-identity-conflict` before anything is sent. A bound value that the
+ deployment settings do not name in this run is kept, and nothing is sent for it. A connection
+ reference's prompting behaviour is never sent: a new one is expected to hold the platform's default,
+ and one changed outside the plugin after it was bound is kept, as a Custom API's implementation is
+ (an edit is complete only while the row still holds the value it was planned over).
+- **Local copy.** Before it reads a protected item into the workspace, the build checks the workspace
+ copy. A protected item whose local copy differs from the server's (an edit an earlier run did not send,
+ or one made by hand), or cannot be compared with it, is refused before anything is written
+ (`workspace-copy-unsent-edits`), and verify stops too; the copy and its binding are kept. Put any change
+ to keep into the spec, then approve replacing the local copy with the server's: the `overwrite:` key the
+ refusal prints, `--authorize overwrite:<kind>:<key>` (for example
+ `--authorize overwrite:customApi:contoso_calc`; the kind is `customApi`, `environmentVariable`,
+ `connectionReference` or `duplicateRule`). With that key the build reads the server's row and puts it in
+ place of the local copy (a create the server never took leaves no copy); if it cannot read that row,
+ it keeps the copy and stops. The key names the item, not a version of its copy: it replaces the local
+ copy as it is when the approved build runs, including any edit made after the stop was printed, as the
+ views' and charts' `overwrite:` key does. Check the copy again before you give it, and do not edit the
+ copy while that build runs. The key is read only with `configurationIdentity: "stable-v1"`.
+ The build never replaces or discards the local copy on its own, also when a protected send fails or its
+ answer is lost: the copy is kept with every edit in it, including one made while the build was sending,
+ and a later build that finds it stops on it until you give that key. Nothing else discards it. The unfinished send
+ itself is still decided from what the build recorded before sending (below); giving the key never sends
+ it again. The build command keeps these items' copies in a working folder of its own and removes it
+ when the command ends, so a copy kept after a failed send lasts until then: the stop applies within
+ that command, and the next command reads the server's rows afresh.
+- **Unfinished work is checked first, declared or not.** Before its first service change, every build
+ reads the binding store for protected items whose create or edit has not finished. If the App Spec no
+ longer declares such an item, the build stops with `managed-settlement-pending` and sends nothing.
+ This applies with or without the field and whatever phases run. Declare the item again, with the
+ field, to finish it.
+ An item that finished before it was removed from the App Spec does not stop the build.
+- **`--changed-only` runs the whole build.** While the field is set, or the binding store holds
+ configuration state, a `--changed-only` apply runs the full build and prints
+ `changed-only: FULL — protected configuration is in play`. Its record of the last apply does not cover
+ these rows, so it cannot tell that one was deleted, that an edit is refused or that the store cannot
+ be read; the full build checks them before its first service change and stops instead. With or without
+ the field, a change to an environment variable, connection reference, Custom API or duplicate-detection
+ rule also makes a `--changed-only` apply a full build.
+- **An edit that did not finish.** The next build decides a Custom API, environment variable or
+ connection reference edit from what the first one recorded before sending. A complete edit is
+ recorded and never sent again. An edit that no request can have reached is sent once, at the same ids.
+ If its target is already there, nothing is sent, and the edit is recorded only if its rows are
+ exactly what the plugin would make: one that needs an approval (a private value) or whose solution
+ membership was removed stops, and is never reported unchanged.
+ If its rows changed since then, it is dropped while nothing was sent; otherwise the build stops until
+ you restore them. Anything else keeps its stop.
+ An edit or create the SDK refuses before its first request (for example a Custom API label edit on an
+ environment with more than one language, `CUSTOM_API_LABELS_UNSUPPORTED`) stops that build and leaves
+ nothing unfinished: the next build is judged on what the App Spec then declares, the earlier
+ declaration, another edit or the same one.
+- **A create that did not finish.** The next build decides it from what the first one recorded before
+ sending, never from today's rows, and sends nothing while it does: a create that is complete is bound;
+ a create that is missing a row, its solution membership or the rule's initial state stops with
+ `create-completion-required` — complete it under the same ids, then build again. An initial
+ publication that failed or whose answer was lost is never sent again by the build: publish the rule
+ under the same id yourself. The one exception is a rule whose content was saved, but whose publish
+ request the record proves was never sent (the run stopped first). The next build sends that publish
+ once, then binds the rule. If the rule's conditions still need your approval, the build asks for it
+ first. Rows that no answer proved this build's own are bound only after you check
+ them and approve each one exactly: the stop (`create-ownership-required`) lists the tokens, such as
+ `adopt:duplicateRule:<key>` and one per child (`adopt:<child kind>:<key>/<child>`, both parts
+ percent-encoded, for example `adopt:customApiRequestParameter:contoso_calc/request%3Aa`). Pass each as
+ printed with its own `--authorize`; a root's token never covers its children, and the tokens are read
+ only with the field and only for declared items. A declaration changed since the create was prepared
+ stops with `managed-pending-intent-changed`: put the original declaration back, finish the create,
+ then make the change. A row that differs from what was sent stops with `create-identity-conflict`.
+- **Retries keep the ids.** When a later step of the same build fails with a transient error and the
+ build runs again, the second attempt finds each protected row at the id the first one bound and sends
+ nothing for it. A protected create whose answer was lost stops the build (`create-outcome-unknown`)
+ and is never retried; the next build decides it as above.
\ No newline at end of file
diff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.md
index 5f56ddb87..d52902b9b 100644
--- a/plugins/model-apps/references/app-spec-schema.md
+++ b/plugins/model-apps/references/app-spec-schema.md
@@ -844,6 +844,7 @@ list with "reach for it when…" guidance.
| `businessRules[].reconcile` | a declared business rule (`reconcile: "declared"` on a rule: created Draft under an id the build keeps, then activated; managed and proved whole, with keyed conditions and actions, OR logic, default values, error messages and recommendations; an existing rule is adopted read-only, never edited) |
| `businessProcessFlows[].reconcile` | a declared business process flow (`reconcile: "declared"` on a flow, with a `key` on every stage and step: created Draft with ids the build keeps, then activated; managed and proved whole, so a rename keeps a stage's or step's id; an existing flow is adopted read-only, never edited, and a removed or reordered stage or step is refused) |
| `createIdentity` | stable create ids for declared views and charts, on a new app only (`createIdentity: "stable-v1"`) |
+| `configurationIdentity` | exact ids and a binding store for declared environment variables, connection references, Custom APIs and duplicate rules (`configurationIdentity: "stable-v1"`, `minimumPluginVersion: "2.23.0"`): a duplicate rule is created and then only verified, and a Custom API takes only single-request or create-only edits |
| `columns[].dateTimeBehavior` | portable schema: calendar-day dates, fixed option values (`{ "value", "label" }`), table search and duplicate detection (`searchEnabled` / `changeTrackingEnabled` / `duplicateDetectionEnabled`) |
## relationships[]
@@ -965,11 +966,13 @@ why they need naming here at all.
front, naming the view and the offending entry.
- **A view takes only these keys:** `entity`, `name`, `description`, `columns`, `sort`, `filters`, `activeOnly`, and — on a view
with `"reconcile": "declared"` — `key`, `viewId`, `linkEntities`. A filter item takes `attr`, `op`, `value`, `values` and
- `relatedEntity`. Any other key is **ignored by the build**, so validation warns about it and names the key it most likely meant
- (`filter` → `filters`, `column` → `attr`, `operator` → `op`); a view written with `filter` would otherwise be built without its
- filter. A view has no `type` (it is always a public view of its table, so leave it out); a `type` an older doc showed is still
- accepted without a warning. These are warnings, never errors — but `lint-app-spec.js --strict` fails on them, so a view with a
- misspelled key stops a `--strict` pipeline instead of building without its filter.
+ `relatedEntity`. Any other key is **refused** (a validation error, so the lint exits 1 without `--strict` and the build stops before it
+ writes anything): the build reads only those keys, so a view written with `filter` would otherwise be built without its filter and list
+ every active row. The message names the key it most likely meant (`filter` → `filters`, `column` → `attr`, `operator` → `op`) and
+ the allowed keys. A view has no `type` (it is always a public view of its table, so leave it out); a `type` an older doc showed is
+ still accepted without a message. Teardown and preview only read a spec that an earlier release may have built, so they accept one with
+ such a key; `verify-model-app.js` reads it too, and reports the finding as a warning. A `--changed-only` apply validates the spec before
+ it decides anything, so an unchanged spec with such a key is refused as well, not reported as nothing to apply.
- `activeOnly` (default `true`) adds `statecode eq 0`. `filters[]` add conditions: `op` is any
FetchXML operator — `eq`/`ne`/`lt`/`le`/`gt`/`ge`/`like`, no-value ops (`eq-userid`, `null`,
`not-null`, `this-week`/`this-month`/`today`/…), and multi-value `in`/`not-in` (use `values[]`).
diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.js
index b3b4b7a41..0e0a46765 100644
--- a/plugins/model-apps/scripts/build-model-app.js
+++ b/plugins/model-apps/scripts/build-model-app.js
@@ -10,12 +10,29 @@
// [--only <phases>] [--skip <phases>] [--from <phase>] [--to <phase>]
// [--workspace <dir>]
// phases: solution,data-model,sample-data,web-resources,views,charts,forms,commands,dashboards,app-shell,pages,ai-features,security,publish
+//
+// Protected configuration (`configurationIdentity: "stable-v1"`, references/app-spec-schema-advanced.md) is checked before the
+// build's first service change. An apply is a full build or exactly --stage data (every other range is refused before anything
+// is sent), and while protected configuration is in play --changed-only runs the full build too, never its no-op or pages-only
+// apply (its snapshot does not describe the configuration rows). Each of these stops sends nothing:
+// configuration-edit-unsupported an edit the protected path does not make (make it outside the plugin)
+// configuration-protected-removal-unsupported a removal (a Custom API child, a bound value's clear)
+// create-identity-opt-in-required the opt-in was removed while the binding store holds a declared item
+// create-identity-unverified the binding store or a namesake lookup cannot be used
+// create-identity-conflict a namesake or a row the binding does not hold stands where a row would go
+// create-completion-required an earlier create is incomplete: complete it under the same ids
+// create-ownership-required rows to bind: pass each printed --authorize adopt:<kind>:... after checking it
+// configuration-row-not-found a bound row is gone (never replaced by a namesake)
+// managed-pending-intent-changed the declaration changed while its create was unfinished
+// managed-settlement-pending an unfinished item the App Spec no longer declares
+// managed-binding-store-unreadable the binding store cannot be read
+// workspace-copy-unsent-edits a local copy differs from the server's: --authorize overwrite:<kind>:<key>
const fs = require('node:fs');
const path = require('node:path');
const { randomUUID } = require('node:crypto');
const { sha256 } = require('./lib/hash.js');
const { validateAppSpec, migrateAppSpec, normalizePageSource, normalizeLanguageCode, specDeclaresAttribute } = require('./lib/app-spec.js');
-const { runSdkBuild, openBuildBindingGroups, planFor, appUniqueName, compileFormIntent, resolveExistingFormId, normalizeFormId, settleOwedPublishes, collectOwedPublishes, settleOwedLengths } = require('./lib/sdk-build.js');
+const { runSdkBuild, openBuildBindingGroups, protectedConfigurationInPlay, planFor, appUniqueName, compileFormIntent, resolveExistingFormId, normalizeFormId, settleOwedPublishes, collectOwedPublishes, settleOwedLengths } = require('./lib/sdk-build.js');
const { authorizeFlag } = require('./lib/cli-failure.js');
const { specTables } = require('./lib/table-publish.js');
const { stagePhasesOrResolve, PHASES, STAGES } = require('./lib/stages.js');
@@ -33,7 +50,7 @@ const { assertSafeOutputDir, assertPlainFileTarget, writeFileSafe } = require('.
const { diffPhases, summarizeDiff } = require('./lib/phase-diff.js');
const { annotateContentHashes, appSourceFileErrors } = require('./lib/content-hash.js');
const { baselinePath, confinedReader, writeBaseline, readBaseline } = require('./lib/deployed-baseline.js');
-const { runChangedOnlyApply, resolveLiveIdentity } = require('./lib/changed-only-flow.js');
+const { runChangedOnlyApply, resolveLiveIdentity, PROTECTED_CONFIGURATION_FULL } = require('./lib/changed-only-flow.js');
const applySnapshotStore = require('./lib/apply-snapshot-store.js');
const { classifyOps, sitemapTargets } = require('./lib/op-diff.js');
const { navigationHolds } = require('./lib/app-navigation.js');
@@ -103,7 +120,7 @@ function assertWorkspaceDir(workspaceDir, { create }) {
// which environment it belongs to, and the answer comes back as `folderNote` so the
// preview can warn that an --apply would stop. Construction is offline (no token
// until first call).
-async function makeSdk(env, spec, workspaceDir, languageCode, { persistent = true, throttle, previewPush = false, publicationBarrier, sendObserver, workflowEffectGate } = {}) {
+async function makeSdk(env, spec, workspaceDir, languageCode, { persistent = true, throttle, previewPush = false, publicationBarrier, sendObserver, workflowEffectGate, managedCreateGate } = {}) {
// A link at the workspace root would make the provision SDK's storage follow it. Refuse
// before either constructor: the first SDK does not use this directory, but once the
// directory has been refused the factory must not run at all.
@@ -120,7 +137,12 @@ async function makeSdk(env, spec, workspaceDir, languageCode, { persistent = tru
// A declared business rule's or process flow's workflow write is screened by the gate of the store that holds its effect
// (lib/deferred-workflow-gate.js): main() makes the gate only when one of those features is on, and the build binds it to its
// store; with no gate the client is made exactly as before.
- const httpClient = createAzHttpClient(env, { throttle, sendOnce: (method, url) => isTranslationExport(method, url) || configurationSendOnce(method, url), ...(publicationBarrier ? { request: publicationBarrier.gateRequest(sendObserver ? sendObserver.wrap() : undefined) } : {}), ...(workflowEffectGate ? { workflowEffectGate } : {}) });
+ // Protected configuration's deferred managed-create gate (lib/managed-create-transport.js), made by main() only while protected
+ // configuration is in play, shares that one slot with it through composeWriteGates: both screen every request, and one both claim is
+ // refused unsent. It is installed on this one client, so the requests the SDK sends without the solution header (an environment
+ // 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 } : {}) });
const sdkTempDir = makeTempWorkspace('model-app-');
const cleanup = () => {
fs.rmSync(sdkTempDir, { recursive: true, force: true });
@@ -602,8 +624,19 @@ function stoppedAfterEarlierAttempts(err, attempt, owedPublishes, owedLengths, w
return halt;
}
+// The validation every build runs on load, with the profile its caller asked for. An APPLY never validates under the structural profile: that profile
+// is for reading a spec (teardown, preview), and it takes the findings an earlier release accepted — an unknown key on a view, which the build drops —
+// as warnings, so a build under it would write the view without that part. The same gate runs before a --changed-only apply may report a success
+// without building (see main), so a spec a build refuses is never certified by a no-op.
+function validateForBuild(spec, opts) {
+ if (opts.apply && opts.profile === 'structural') {
+ return { ok: false, errors: ["a build that applies cannot validate under the 'structural' profile, which reads a spec to tear it down or preview it and lets findings through that a build must refuse: use 'plan' or 'deploy'"] };
+ }
+ return validateAppSpec(spec, { profile: opts.profile || 'deploy' });
+}
+
async function buildModelApp(spec, opts, deps) {
- const v = validateAppSpec(spec, { profile: opts.profile || 'deploy' });
+ const v = validateForBuild(spec, opts);
if (!v.ok) {
return { ok: false, errors: v.errors };
}
@@ -791,7 +824,7 @@ 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]
+ const authorizeGiven = [opts.authorizedDestructive, opts.authorizedAdoption, opts.authorizedOverwrite, opts.authorizedWebResourceAdoption, opts.authorizedWebResourceOverwrite, opts.publicationRisk, opts.configurationApprovals]
.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) {
@@ -945,6 +978,10 @@ async function buildModelAppHeld(spec, opts, deps, v, buildLease) {
...(deps.sendObserver ? { sendObserver: deps.sendObserver } : {}),
// The client's workflow effect gate (lib/deferred-workflow-gate.js), which the engine binds to this store.
...(deps.workflowEffectGate ? { workflowEffectGate: deps.workflowEffectGate } : {}),
+ // Protected configuration's managed-create gate (made only while protected configuration is in play), which the engine binds
+ // 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 } : {}),
sdk: deps.sdk,
provisionSdk: deps.provisionSdk,
owedLengths,
@@ -1339,6 +1376,13 @@ const readLanguageFlag = (flags) => readAliasedFlag(flags, 'language-code', 'lan
// overwrite:chart:<table>/<name> that differs from the server's (sdk-build.js, refuseUnsentCopy)
// overwrite:quickfind:<table> replacing a local copy of a table's Quick Find view (entities[].quickFind) that differs
// from the server's; a Quick Find view is never adopted and has no server drift
+// overwrite:<kind>:<declared key> replacing a protected configuration item's local copy (configurationIdentity "stable-v1";
+// kind customApi, environmentVariable, connectionReference or duplicateRule) that differs
+// from the server's (lib/configuration-protected.js; read by configurationAuthorizationKeys)
+// adopt:<kind>:<declared key> binding the row of a protected configuration item that an earlier, unfinished build may have
+// adopt:<child kind>:<key>/<child> created and whose answer was lost (child kind environmentVariableValue, customApiRequestParameter,
+// customApiResponseProperty or duplicateRuleCondition; both parts percent-encoded), exactly as
+// the stop printed it; one row each, a root's never covers its children (configurationApprovals)
// The family is part of the key because ids collide across families: a view and a chart may share <table>/<name>, and a view
// may be named "quickFind". Each approval is stored under its family-typed id (reconcile-common.js approvalKey, the flag minus
// its verb) and each guard asks only for its own family, so consent to one artifact never reaches another. The untyped form
@@ -1388,10 +1432,18 @@ function authorizationKeys(argv, spec) {
const configuration = configurationAuthorizationKeys(raw.filter((k) => !hasNul(k)), spec);
const keys = new Set(configuration.keys);
const adopt = new Set();
- const overwrite = new Set();
+ // overwrite:<configuration kind>:<declared key> (a protected item's local copy, lib/configuration-protected.js) is claimed and checked
+ // there and stored as <kind>:<key>, a family no view, chart or other approval spells.
+ const overwrite = new Set(configuration.overwrite || []);
const problems = nulKeys.map((key) => `'${key.replace(/\u0000/g, '\\u0000')}' holds a NUL character (U+0000), which a command-line argument cannot carry; give the item a name without it`).concat(configuration.problems.map(({ token, code }) => (code === 'CONFIGURATION_AUTHORIZATION_UNKNOWN_ITEM'
? `'${token}' names a configuration item the spec does not declare`
- : `'${token}' is not <kind>:<declared key>:<field> for a field a configuration change can consent to`)));
+ : code === 'CONFIGURATION_OVERWRITE_UNPROTECTED'
+ ? `'${token}' replaces a protected configuration item's local copy, and the spec does not set configurationIdentity "stable-v1", so there is no such copy to replace`
+ : code === 'CONFIGURATION_ADOPT_UNPROTECTED'
+ ? `'${token}' binds a row of a protected configuration item, and the spec does not set configurationIdentity "stable-v1", so there is no such row to bind`
+ : 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`)));
// 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.
@@ -1635,7 +1687,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, error: problems.length ? `--authorize: ${problems.join('; ')}` : null };
+ return { keys, adopt, overwrite, webResourceAdopt, webResourceOverwrite, publicationRisk, configurationApprovals: configuration.rowApprovals || new Set(), error: problems.length ? `--authorize: ${problems.join('; ')}` : null };
}
function parseLanguageCode(value) {
@@ -1862,6 +1914,7 @@ async function main() {
...(authorization.webResourceAdopt.size ? { authorizedWebResourceAdoption: authorization.webResourceAdopt } : {}),
...(authorization.webResourceOverwrite.size ? { authorizedWebResourceOverwrite: authorization.webResourceOverwrite } : {}),
...(authorization.publicationRisk.size ? { publicationRisk: authorization.publicationRisk } : {}),
+ ...(authorization.configurationApprovals.size ? { configurationApprovals: authorization.configurationApprovals } : {}),
nonInteractive: flags['non-interactive'] === true || envTruthy(process.env.POWER_PLATFORM_SKILLS_NONINTERACTIVE),
languageCode,
appDir: path.dirname(specPath),
@@ -1992,7 +2045,13 @@ async function runBuildCommand({ env, spec, languageCode, changedOnly, workspace
// The workflow effect gate of declared business rules and process flows, bound to the managed binding store once the build opens
// it (lib/deferred-workflow-gate.js). Made only while one of those features is on, so with both off the client is unchanged.
const workflowEffectGate = declaredFeatureOn('rules') || declaredFeatureOn('bpf') ? require('./lib/deferred-workflow-gate.js').createDeferredWorkflowGate() : 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 } : {}) });
+ // Protected configuration's deferred managed-create gate, made only for an apply where protected configuration is in play: the App
+ // Spec sets configurationIdentity "stable-v1", or the workspace's binding store still holds configuration state after the opt-in was
+ // removed (sdk-build.js protectedConfigurationInPlay, a local read that sends nothing). Otherwise none is made and no protected module
+ // 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 } : {}) });
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).
@@ -2049,6 +2108,7 @@ async function runBuildCommand({ env, spec, languageCode, changedOnly, workspace
warn: (m) => process.stderr.write(`⚠ ${m}\n`),
sdk, provisionSdk, journal, throttle, stepTally, publicationBarrier, sendObserver,
...(workflowEffectGate ? { workflowEffectGate } : {}),
+ ...(managedCreateGate ? { managedCreateGate } : {}),
...(previewHttpClient ? { previewHttpClient } : {}),
// The role-privileges check must actually RUN here. verify-spec skips it unless BOTH
// `rolePrivileges` and `entityPrivileges` readers are present, and `entityPrivileges` used to
@@ -2074,12 +2134,23 @@ async function runBuildCommand({ env, spec, languageCode, changedOnly, workspace
// dashboard write that creates a tile (dashboard-reconcile.js tileCaptionLanguages).
provisionedLanguages: () => readProvisionedLanguages(env),
};
- if (changedOnly && opts.apply) {
+ // Protected configuration in play (the managed-create gate exists) takes no changed-only shortcut: its debt sweep, its opt-in-removed
+ // stop and its read-only preflight run in the engine before the build's first service change, and the snapshot a no-op or a fast
+ // apply would trust does not describe the configuration rows (an unreadable store, a bound row deleted, an edit the protected path
+ // refuses all leave it as it was). So such a --changed-only apply is the full build below, which also applies the edits; a pending
+ // obligation stops it, never a success.
+ if (changedOnly && opts.apply && !managedCreateGate) {
// #changed-only: the flow decides fast (pages-only via the sdk-build seams) vs full, gated on the
// persisted snapshot's eligibility + a live identity check (WhoAmI orgId + app discovery). It calls
// buildModelApp itself (injected) and manages the snapshot lifecycle (invalidate-before-write +
// re-bless-on-success). readContent + WhoAmI are injected so the flow is testable offline.
- r = await runChangedOnlyApply({
+ // The flow can end in a success that never calls buildModelApp (a no-op over an unchanged spec), and an earlier release accepted specs
+ // that the build now refuses (a view written with `filter`): validate first, as the build does, so such a spec is refused here rather
+ // than certified by a baseline written for it. Only a refusal returns; a spec that passes is validated again by the build it reaches,
+ // which is the one that narrates the warnings.
+ const gate = validateForBuild(spec, opts);
+ if (!gate.ok) r = { ok: false, errors: gate.errors };
+ else r = await runChangedOnlyApply({
spec, opts,
deps: {
...deps,
@@ -2106,7 +2177,9 @@ async function runBuildCommand({ env, spec, languageCode, changedOnly, workspace
// contention from a concurrent run, an unwritable workspace), that later run certifies pre-apply
// state and can skip work this apply just made necessary.
if (opts.apply) assertSnapshotInvalidated(applySnapshotStore, workspaceDir);
+ if (changedOnly && opts.apply) deps.log(`▸ changed-only: FULL — ${PROTECTED_CONFIGURATION_FULL}`);
r = await buildModelApp(spec, opts, deps);
+ if (changedOnly && opts.apply && r && typeof r === 'object') r = { ...r, changedOnly: { decision: 'full', reason: PROTECTED_CONFIGURATION_FULL } };
}
} finally {
cleanup();
diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.js
index 1019d04e7..bf671d2f3 100644
--- a/plugins/model-apps/scripts/lib/app-spec.js
+++ b/plugins/model-apps/scripts/lib/app-spec.js
@@ -1158,11 +1158,11 @@ function reportUnknownAppShellKeys(node, level, where, errors) {
// The keys the build READS on a `views[]` entry (viewDef in sdk-build.js; compileViewIntent in view-reconcile.js, which also reads `key`,
// `viewId` and `linkEntities` of a declared view; `description` is written to the view by both) and on each of its filter items
// (`attr`, `op`, `value`, `values`; `relatedEntity` scopes a condition to a declared join). Any other key is dropped without a trace,
-// so a view written with `filter` instead of `filters` was built WITHOUT its filter and listed every active row (#799). Frozen, in the
+// so a view written with `filter` instead of `filters` was built WITHOUT its filter and listed every active row (#799, #827). Frozen, in the
// order the messages list them.
const VIEW_KEYS = Object.freeze(['entity', 'name', 'description', 'columns', 'sort', 'filters', 'activeOnly', 'reconcile', 'key', 'viewId', 'linkEntities']);
const VIEW_FILTER_KEYS = Object.freeze(['attr', 'op', 'value', 'values', 'relatedEntity']);
-// Keys no code reads that are nevertheless accepted without a warning, because the docs and samples of earlier releases showed them
+// Keys no code reads that are nevertheless accepted without a message, because the docs and samples of earlier releases showed them
// and they never changed what is built. Frozen: the list is closed, a new entry needs the same reason.
const IGNORED_VIEW_KEYS = Object.freeze(['type']);
@@ -1170,10 +1170,9 @@ const IGNORED_VIEW_KEYS = Object.freeze(['type']);
// and `activeonly` are caught by the single-edit matcher). Prototype-less for the reason ENTITY_KEY_HINTS is: the lookup key comes from the
// spec.
//
-// `type` is deliberately not warned about (see IGNORED_VIEW_KEYS): older docs and the shipped
-// samples put it on a view, it never had an effect (a view is always a public view of its table), and a spec written from them must keep
-// passing `lint-app-spec.js --strict`, which fails on any warning. The keys that DO warn are the ones whose silent loss changes the view
-// (a misspelled `filters` drops the filter), so `--strict` failing on those is intended.
+// `type` is deliberately not reported (see IGNORED_VIEW_KEYS): older docs and the shipped samples put it on a view, it never had an effect
+// (a view is always a public view of its table), and a spec written from them must keep validating. The keys that ARE reported are the
+// ones whose silent loss changes the view (a misspelled `filters` drops the filter).
const VIEW_KEY_HINTS = Object.assign(Object.create(null), {
where: " — did you mean 'filters'?",
conditions: " — did you mean 'filters'?",
@@ -1194,12 +1193,14 @@ const VIEW_FILTER_KEY_HINTS = Object.assign(Object.create(null), {
entity: " — did you mean 'relatedEntity'? Only a condition on a declared join takes one",
});
-// The warnings for the keys of one `views[]` entry and of its filter items (`filters[]`, and the `filters[]` of each `linkEntities[]` join, which are
+// The findings for the keys of one `views[]` entry and of its filter items (`filters[]`, and the `filters[]` of each `linkEntities[]` join, which are
// the same shape), each with `vlabel` in front: one per unknown key, naming the key it most likely meant (a written hint first, then the shared
-// single-edit matcher, which also settles a casing slip). A WARNING, not an error: the build has always ignored such a key, so a spec that
-// carries one still builds as before, and one a release before this check validated clean must keep validating. Only a plain object is
-// inspected — a non-object entry or filter is reported by the shape checks — and enumeration is guarded because the spec comes from the caller.
-function viewKeyWarnings(v, vlabel) {
+// single-edit matcher, which also settles a casing slip). The caller decides whether they are errors or warnings (see `viewKeyFindings`): every
+// profile that builds or plans a build refuses them. They were warnings (#799), but a key the build drops silently changes what is built — a view
+// written with `filter` listed every active row while the author told the maker it was filtered — and a warning among the advisory ones was not
+// acted on, so the build now stops before it writes anything (#827), as it does for an unknown key of a form's `fieldOptions` entry. Only a plain
+// object is inspected — a non-object entry or filter is reported by the shape checks — and enumeration is guarded because the spec comes from the caller.
+function viewKeyProblems(v, vlabel) {
const unknown = (obj, allowed, hints, where, accepted = []) => {
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return [];
let keys;
@@ -1215,7 +1216,7 @@ function viewKeyWarnings(v, vlabel) {
const meant = near && allowed.find((a) => a.toLowerCase() === near);
hint = meant ? ` — did you mean '${meant}'?` : '';
}
- return `${vlabel}: ${where ? `${where}: ` : ''}unknown key '${k}'${hint}; the build ignores it (allowed: ${allowed.join(', ')})`;
+ return `${vlabel}: ${where ? `${where}: ` : ''}unknown key '${k}'${hint}; the build does not read it, so it is refused rather than built without it (allowed: ${allowed.join(', ')})`;
});
};
const out = unknown(v, VIEW_KEYS, VIEW_KEY_HINTS, '', IGNORED_VIEW_KEYS);
@@ -2104,6 +2105,9 @@ const APP_THEME_MIN_VERSION = '2.21.0';
// createIdentity: "stable-v1" (stable create ids for declared views and charts) first shipped in 2.21.0.
const CREATE_IDENTITY_MIN_VERSION = '2.21.0';
const CREATE_IDENTITY_STABLE = 'stable-v1';
+// configurationIdentity: "stable-v1" (exact ids and a binding store for declared environment variables, connection references,
+// Custom APIs and duplicate detection rules) first ships in 2.23.0. It takes the same one value as createIdentity.
+const CONFIGURATION_IDENTITY_MIN_VERSION = '2.23.0';
const isPluginVersion = (value) => typeof value === 'string' && /^\d+(?:\.\d+)*(?:[-+][0-9A-Za-z.-]+)?$/.test(value);
// Declared reconciliation (views, charts and web resources with reconcile: "declared", a view's viewId pin and joins, a chart title, command
// keys and row pins, a table's quickFind): an older plugin ignores these fields (or, for quickFind, refuses the table), so a
@@ -2288,6 +2292,10 @@ function appMembershipWarnings(spec) {
&& (!isPluginVersion(floor) || compareVersions(floor, CREATE_IDENTITY_MIN_VERSION) < 0)) {
warnings.push(`set minimumPluginVersion to '${CREATE_IDENTITY_MIN_VERSION}' or newer when using createIdentity — older plugins ignore it and create with fresh ids`);
}
+ if (Object.prototype.hasOwnProperty.call(spec, 'configurationIdentity')
+ && (!isPluginVersion(floor) || compareVersions(floor, CONFIGURATION_IDENTITY_MIN_VERSION) < 0)) {
+ warnings.push(`set minimumPluginVersion to '${CONFIGURATION_IDENTITY_MIN_VERSION}' or newer when using configurationIdentity — older plugins ignore it, keep no binding store for configuration and find it by name`);
+ }
if (app.tables === undefined && app.mainForms === undefined) return warnings;
if (!isPluginVersion(floor) || compareVersions(floor, APP_MEMBERSHIP_MIN_VERSION) < 0) {
warnings.push(`set minimumPluginVersion to '${APP_MEMBERSHIP_MIN_VERSION}' or newer when using app.tables or app.mainForms — older plugins ignore these fields`);
@@ -2775,6 +2783,11 @@ function validateAppSpec(spec, opts = {}) {
// accepted and built a spec carrying one — so the structural profile and read-only verification (`primaryAttributeKeys: 'warn'`) take it
// as a warning in the same words.
const primaryAttributeKeyFindings = profile === 'structural' || opts.primaryAttributeKeys === 'warn' ? warnings : errors;
+ // Where an unknown key of a `views[]` entry or of one of its filter items goes (viewKeyProblems), by the same arrangement again: the build
+ // drops such a key, so every profile that builds or plans a build keeps it an error, while a release before the check accepted and built a
+ // spec carrying one (the view without its filter) — so the structural profile and read-only verification (`viewKeys: 'warn'`) take it as a
+ // warning in the same words, and an app built from such a spec can still be torn down, previewed and verified.
+ const viewKeyFindings = profile === 'structural' || opts.viewKeys === 'warn' ? warnings : errors;
if (!VALIDATION_PROFILES.includes(profile)) {
return { ok: false, errors: [`unknown validation profile '${profile}' (valid: ${VALIDATION_PROFILES.join(', ')})`], warnings };
}
@@ -2808,6 +2821,12 @@ function validateAppSpec(spec, opts = {}) {
// the stable-identity modules, and creates-identity.js requires this module. A test pins the two to one value.
errors.push(`create-identity-invalid: createIdentity must be "${CREATE_IDENTITY_STABLE}" or absent; got ${JSON.stringify(spec.createIdentity)}`);
}
+ // configurationIdentity: absent, or exactly "stable-v1" (exact ids and a binding store for the declared environment variables,
+ // connection references, Custom APIs and duplicate detection rules). Like createIdentity, any other value is refused and never
+ // read as absent: a typo must not fall back to name lookups on the build that was meant to keep exact ids.
+ if (Object.prototype.hasOwnProperty.call(spec, 'configurationIdentity') && spec.configurationIdentity !== CREATE_IDENTITY_STABLE) {
+ errors.push(`create-identity-invalid: configurationIdentity must be "${CREATE_IDENTITY_STABLE}" or absent; got ${JSON.stringify(spec.configurationIdentity)}`);
+ }
if (spec.minimumPluginVersion !== undefined) {
const want = spec.minimumPluginVersion;
// ANCHORED at BOTH ends on purpose. A prefix-only pattern accepted `2..9` on its leading `2`,
@@ -3450,7 +3469,7 @@ function validateAppSpec(spec, opts = {}) {
else v.filters.forEach((f, i) => attrRef(f && f.attr, `filters[${i}].attr`));
}
if (v && v.reconcile !== undefined && v.reconcile !== 'declared') errors.push(`${vlabel}: reconcile must be "declared" (or left out)`);
- warnings.push(...viewKeyWarnings(v, vlabel));
+ viewKeyFindings.push(...viewKeyProblems(v, vlabel));
if (isDeclaredView(v)) {
// compileViewIntent walks columns, sort, filters and joins as lists; a non-list one is already reported above (or by
// the shape normalization), so it is not walked again into a TypeError.
@@ -5006,6 +5025,7 @@ module.exports = {
APP_THEME_MIN_VERSION,
CREATE_IDENTITY_MIN_VERSION,
CREATE_IDENTITY_STABLE,
+ CONFIGURATION_IDENTITY_MIN_VERSION,
isPluginVersion,
sitemapEntityTables,
appMembershipWarnings,
diff --git a/plugins/model-apps/scripts/lib/changed-only-flow.js b/plugins/model-apps/scripts/lib/changed-only-flow.js
index 68a8dc5ed..e6d61e5a9 100644
--- a/plugins/model-apps/scripts/lib/changed-only-flow.js
+++ b/plugins/model-apps/scripts/lib/changed-only-flow.js
@@ -32,6 +32,9 @@ const { odataLit } = require('./odata.js');
const { withAppBuildLease, applyWorkspaceOf } = require('./app-operation-lease.js');
const { appUniqueName } = require('./sdk-build.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';
+
// ---- PURE decision ------------------------------------------------------------------------------------
// Decide fast vs full vs noop from the annotated spec, the persisted snapshot, and the live identity. `distrust` is the
@@ -331,6 +334,14 @@ async function runChangedOnlyApplyHeld({ spec, opts, deps }) {
if (opts.sampleData && snapshot && snapshot.sampleDataApplied !== true && (decision.decision === 'fast' || decision.decision === 'noop')) {
decision = { ...decision, decision: 'full', reason: '--sample-data requested but the baseline did not seed rows — full build' };
}
+ // Protected configuration (configurationIdentity "stable-v1", or a binding store still holding configuration state) is checked only by
+ // the full build: its debt sweep, its opt-in-removed stop and its read-only preflight run there, before the first write, and its edits
+ // are applied there. The snapshot does not describe those rows (a bound row deleted, an unreadable store or an edit the protected path
+ // refuses all leave the spec's slices as they were), so a fast or no-op decision would report success over a pending obligation.
+ // build-model-app.js never runs this flow while its managed-create gate exists; this is the same rule for any other caller.
+ if (deps.managedCreateGate && (decision.decision === 'fast' || decision.decision === 'noop')) {
+ decision = { ...decision, decision: 'full', reason: PROTECTED_CONFIGURATION_FULL };
+ }
log(`▸ changed-only: ${decision.decision.toUpperCase()} — ${decision.reason}`);
if (decision.decision === 'noop') {
@@ -534,4 +545,5 @@ module.exports = {
runChangedOnlyApply,
fullApplyOpts,
distrustWorkspace,
+ PROTECTED_CONFIGURATION_FULL,
};
diff --git a/plugins/model-apps/scripts/lib/configuration-artifacts.js b/plugins/model-apps/scripts/lib/configuration-artifacts.js
index 1101e5b17..d2a648c04 100644
--- a/plugins/model-apps/scripts/lib/configuration-artifacts.js
+++ b/plugins/model-apps/scripts/lib/configuration-artifacts.js
@@ -652,6 +652,16 @@ function identityStop(code, id) {
return error;
}
+// Under an exact port the row its binding names is read into the workspace with a fetch that OVERWRITES the local copy.
+// A copy that holds edits the service has not seen (an earlier run's unsent change, or one made by hand) is the maker's to
+// keep or drop, never this read's: it stops typed, the copy kept (the protected preflight names it first, as
+// workspace-copy-unsent-edits with the one approval that replaces it, overwrite:<kind>:<key>). Only a diff (lib/unsynced-edits.js), no request; a copy the workspace does not hold reads clean, and a diff
+// that cannot be made reads as edits, so a doubtful copy is kept too.
+async function refuseLocalDraft(sdk, kind, id) {
+ const { hasUnsyncedEdits } = require('./unsynced-edits.js');
+ if (await hasUnsyncedEdits(sdk, kind, id)) throw identityStop('create-completion-required', id);
+}
+
// The id a typed stop is about, when it names one, so a maker can inspect the row the next run could not read. The
// stops of a stable port's resolver carry the create they stop, e.g.
// { code: 'create-identity-unverified', message: '... could not be read (HTTP 503: ...)', create: { kind, key, id } }
@@ -686,9 +696,17 @@ async function adoptionOf(managed, kind, key, id, remote, origin) {
return { id, remote, origin };
}
+// An exact port (protected configuration, lib/configuration-protected.js) is the one authority on the kinds it protects:
+// its binding store, read at exact ids, decides, and no other record (the managed-artifacts manifest) or name may stand in.
+function exactPortOf(ctx, kind) {
+ const port = portOf(ctx);
+ return port && port.exact === true && typeof port.protects === 'function' && port.protects(kind) ? port : null;
+}
+
async function locate(ctx, kind, key, identity) {
const managed = ctx.managed;
- if (managed && typeof managed.lookup === 'function') {
+ const exactPort = exactPortOf(ctx, kind);
+ if (!exactPort && managed && typeof managed.lookup === 'function') {
const bound = await managed.lookup(kind, key);
if (bound && bound.id) {
try {
@@ -716,7 +734,13 @@ async function locate(ctx, kind, key, identity) {
throw identityStop(portCode(error) || 'create-identity-unverified', stoppedId(error));
}
if (resolved && resolved.state === 'present' && typeof resolved.id === 'string' && resolved.id) {
- return adoptionOf(managed, kind, key, resolved.id, await ctx.sdk.fetchArtifact(kind, resolved.id, { overwrite: true }), 'resolved');
+ if (exactPort) await refuseLocalDraft(ctx.sdk, kind, resolved.id);
+ const remote = await ctx.sdk.fetchArtifact(kind, resolved.id, { overwrite: true });
+ // An exact port proved the row is this build's own create (its committed binding, read at the exact id): it is
+ // not adopted, so the adoption policy and the manifest's record are not asked — the binding store answers. A write
+ // the port still owes for it (an unsent pending edit) rides along: planOne never counts such an item unchanged.
+ if (exactPort) return { id: resolved.id, remote, origin: 'resolved', ...(resolved.owed ? { owed: resolved.owed } : {}) };
+ return adoptionOf(managed, kind, key, resolved.id, remote, 'resolved');
}
if (!resolved || resolved.state !== 'absent') throw identityStop('create-identity-unverified');
derived = typeof resolved.id === 'string' && resolved.id ? resolved.id : null;
@@ -771,6 +795,9 @@ async function planOne(ctx, kindPlan, entry, plan) {
// A clear the maker asked for, with its exact token, is applied: the requirement is then a readiness result of
// the row read back (ENVIRONMENT_VARIABLE_VALUE_MISSING stops the build), not a reason to keep the old value.
if (missing && !(kindPlan.consentedClear && kindPlan.consentedClear(entry, compared, ctx))) return refuse(missing, found.id);
+ // An exact port still owes a write for this item (an unsent pending edit) that the comparison does not see: success
+ // here would leave that attempt pending behind a clean result, so the item stops, typed, before anything is sent.
+ if (found.owed && !compared.changes.length) return refuse(found.owed.code, found.id);
const action = compared.changes.length ? 'update' : 'unchanged';
const op = operation(kind, key, target, action, {
id: found.id,
@@ -779,7 +806,7 @@ async function planOne(ctx, kindPlan, entry, plan) {
destructive: compared.destructive === true,
...(compared.authorize && compared.authorize.length ? { authorize: compared.authorize } : {}),
});
- op.detail = { entry, identity: kindPlan.identity(entry), remote: found.remote, childIds: found.childIds, changes: compared.changes, singleWrite: compared.singleWrite === true, unrecorded: found.unrecorded === true };
+ op.detail = { entry, identity: kindPlan.identity(entry), remote: found.remote, childIds: found.childIds, changes: compared.changes, singleWrite: compared.singleWrite === true, unrecorded: found.unrecorded === true, ...(found.owed ? { owed: found.owed } : {}) };
if (kindPlan.bound) op.detail.bound = kindPlan.bound(entry, found.remote);
plan.operations.push(op);
return op;
@@ -1972,9 +1999,36 @@ async function applyUpdate(op, ctx, result, known) {
return answer && answer.result;
};
+ // Under an exact port that edits this kind itself (protected configuration), the whole edit — new children included —
+ // is ONE attempt of the port: the children take the ids its plan derived (never one per child through `run`), and the
+ // one push runs inside that attempt's create set, which proves and records it.
+ const exactPort = portOf(ctx);
+ const exactUpdate = exactPort && exactPort.exact === true && typeof exactPort.update === 'function' && typeof exactPort.updates === 'function' && exactPort.updates(kind) ? exactPort : null;
+ const updateExactly = async () => {
+ let entered = false;
+ try {
+ const answer = await exactUpdate.update({ kind, key: portKeyOf(kind, key), id }, async ({ childIds: plannedIds = {} }) => {
+ entered = true;
+ for (const { change, child } of created) {
+ const childId = plannedIds[child.slot];
+ if (!childId) throw tagged(child.kind, key, 'create-identity-unverified', 'nothing');
+ placeChild(change, child, childId);
+ childIds[child.slot] = childId;
+ }
+ handle.ids = { id, childIds: { ...childIds } };
+ return write();
+ });
+ return answer.result;
+ } catch (error) {
+ if (error && error[TAGGED]) throw error;
+ const routed = routeFailure(error, entered);
+ throw tagged(kind, key, routed.code, entered ? 'unknown' : 'nothing', routed);
+ }
+ };
+
let pushed;
try {
- pushed = await level(0);
+ pushed = exactUpdate ? await updateExactly() : await level(0);
} catch (error) {
const routed = routeFailure(error, false);
// A write (not a create) whose answer was lost: what it changed is not known.
@@ -2209,7 +2263,9 @@ async function applyConfiguration(plan, ctx) {
if (!blocked && await typesUnreadable(['duplicateRuleCondition'], added.map((child) => child.key))) continue;
}
}
- if (op.action === 'update' || (op.action === 'unchanged' && !stopped)) {
+ // An owed edit's membership is added by the port inside that edit's own attempt (configuration-protected.js update),
+ // never here outside it.
+ if ((op.action === 'update' && !(op.detail && op.detail.owed)) || (op.action === 'unchanged' && !stopped)) {
const joined = await membership.ensure(op);
if (joined) {
pushFinding(result, joined.bucket, { kind, key, id: op.id, code: joined.code, unit: 'membership' });
@@ -2289,6 +2345,8 @@ async function reconcileChildRecords(plan, ctx, result) {
const sameItem = (op) => (line) => line.kind === op.kind && line.key === op.key;
for (const op of plan.operations || []) {
if (!op.detail || !CHILD_KINDS[op.kind] || (op.action !== 'update' && op.action !== 'unchanged')) continue;
+ // Under an exact port every child is a row of the root's committed binding, proved at its exact id: not adopted.
+ if (exactPortOf(ctx, op.kind)) continue;
// A root whose own management is unconfirmed is reported as such already; its children wait for it.
if (op.detail.unrecorded) continue;
if (![...result.saved, ...result.unchanged].some(sameItem(op))) continue;
@@ -2550,18 +2608,97 @@ const TOKEN_ROOTS = Object.freeze({
// Sort the `--authorize` tokens the maker passed: those of this module's kinds are checked against the App Spec
// (the root must be declared; the field must be one a plan can ask for) and normalized exactly as a plan writes them
// (lower-cased names and child names; a rule's key and a condition's key byte for byte). Tokens of other kinds are
-// answered unclaimed, for their own grammar. `{keys: Set, problems: [{token, code}], unclaimed: [token]}`.
+// answered unclaimed, for their own grammar. `{keys: Set, overwrite: Set, rowApprovals: Set, problems: [{token, code}], unclaimed: [token]}`.
+// `overwrite:<kind>:<declared key>` (e.g. overwrite:customApi:contoso_Calc) is the one approval that replaces a protected
+// item's local workspace copy with the server's (lib/configuration-protected.js, the preflight's stop on a copy that
+// differs). It names a whole root item, matched as the other tokens are (a duplicate rule's key exactly), and is read only
+// under `configurationIdentity: "stable-v1"`: the ordinary path never stops on a configuration copy, so the token would
+// approve nothing. It lands in `overwrite` as `<kind>:<port key>` (the flag minus its verb, reconcile-common.js approvalKey).
+const OVERWRITE_TOKEN = /^overwrite:(environmentVariable|connectionReference|customApi|duplicateRule):([\s\S]+)$/;
+// `adopt:<kind>:<declared key>` and `adopt:<child kind>:<root key>/<slot>` approve binding ONE row that an earlier,
+// unfinished protected create may have made and whose answer was lost (lib/managed-create-context.js judgeRows). The
+// preflight prints them in the context's spelling (defaultApprovalToken): a root as adopt:<kind>:<port key>, a child as
+// adopt:<child kind>:<encodeURIComponent(port key)>/<encodeURIComponent(slot)>, e.g.
+// adopt:duplicateRule:email
+// adopt:environmentVariableValue:contoso_apibase/value
+// adopt:customApiRequestParameter:contoso_calc/request%3Aa
+// adopt:duplicateRuleCondition:email/e
+// Read only under the opt-in, checked against the App Spec (the root and the child must be declared) and normalized back
+// to that spelling, so a key typed in another case still names the one row; a root's approval never covers its children.
+const ADOPT_ROOT_TOKEN = /^adopt:(environmentVariable|connectionReference|customApi|duplicateRule):([\s\S]+)$/;
+const ADOPT_CHILD_TOKEN = /^adopt:(environmentVariableValue|customApiRequestParameter|customApiResponseProperty|duplicateRuleCondition):([\s\S]+)$/;
+const ADOPT_CHILD_PARENT = Object.freeze({
+ environmentVariableValue: 'environmentVariable', customApiRequestParameter: 'customApi', customApiResponseProperty: 'customApi', duplicateRuleCondition: 'duplicateRule',
+});
function configurationAuthorizationKeys(tokens, spec) {
const keys = new Set();
+ const overwrite = new Set();
+ const rowApprovals = new Set();
const problems = [];
const unclaimed = [];
+ const declaredRoots = (kind) => {
+ const [list, field] = TOKEN_ROOTS[kind];
+ return Array.isArray(spec && spec[list]) ? spec[list].filter(isObject).map((e) => e[field]).filter(nonEmptyString) : [];
+ };
+ const declaredEntry = (kind, root) => {
+ const [list, field] = TOKEN_ROOTS[kind];
+ return (Array.isArray(spec && spec[list]) ? spec[list] : []).find((e) => isObject(e) && e[field] === root) || null;
+ };
+ const rootOf = (kind, name) => declaredRoots(kind).find((n) => (kind === 'duplicateRule' ? n === name : lower(n) === lower(name)));
+ const decode = (text) => {
+ try { return decodeURIComponent(text); } catch { return null; }
+ };
+ // The child's slot as the protected plan keys it (configuration-create-bindings.js planOf), or null when the App Spec
+ // declares no such child: an environment variable's one value, a Custom API parameter or property by its lower-cased
+ // unique name, a duplicate rule's condition by its key exactly.
+ const slotOf = (childKind, entry, slot) => {
+ if (childKind === 'environmentVariableValue') return slot === 'value' ? 'value' : null;
+ if (childKind === 'duplicateRuleCondition') return (Array.isArray(entry.conditions) ? entry.conditions : []).some((c) => isObject(c) && c.key === slot) ? slot : null;
+ const [prefix, list] = childKind === 'customApiRequestParameter' ? ['request:', entry.requestParameters] : ['response:', entry.responseProperties];
+ const name = lower(slot).startsWith(prefix) ? lower(slot).slice(prefix.length) : null;
+ return name && (Array.isArray(list) ? list : []).some((c) => isObject(c) && lower(c.uniqueName) === name) ? `${prefix}${name}` : null;
+ };
+ const protectedSpec = isObject(spec) && spec.configurationIdentity === 'stable-v1';
for (const token of tokens || []) {
const text = typeof token === 'string' ? token : '';
+ const replace = OVERWRITE_TOKEN.exec(text);
+ if (replace) {
+ const [, kind, name] = replace;
+ const root = rootOf(kind, name);
+ if (!root) problems.push({ token: text, code: 'CONFIGURATION_AUTHORIZATION_UNKNOWN_ITEM' });
+ else if (!protectedSpec) problems.push({ token: text, code: 'CONFIGURATION_OVERWRITE_UNPROTECTED' });
+ else overwrite.add(`${kind}:${portKeyOf(kind, root)}`);
+ continue;
+ }
+ const adoptRoot = ADOPT_ROOT_TOKEN.exec(text);
+ if (adoptRoot) {
+ const [, kind, name] = adoptRoot;
+ const root = rootOf(kind, name);
+ if (!root) problems.push({ token: text, code: 'CONFIGURATION_AUTHORIZATION_UNKNOWN_ITEM' });
+ else if (!protectedSpec) problems.push({ token: text, code: 'CONFIGURATION_ADOPT_UNPROTECTED' });
+ else rowApprovals.add(`adopt:${kind}:${portKeyOf(kind, root)}`);
+ continue;
+ }
+ const adoptChild = ADOPT_CHILD_TOKEN.exec(text);
+ if (adoptChild) {
+ const [, childKind, rest] = adoptChild;
+ const parent = ADOPT_CHILD_PARENT[childKind];
+ // Both parts are percent-encoded, so the one '/' is the separator; anything else is not a key the build printed.
+ const parts = rest.split('/');
+ const name = parts.length === 2 ? decode(parts[0]) : null;
+ const slot = parts.length === 2 ? decode(parts[1]) : null;
+ if (!nonEmptyString(name) || !nonEmptyString(slot)) { problems.push({ token: text, code: 'CONFIGURATION_ADOPT_INVALID' }); continue; }
+ const root = rootOf(parent, name);
+ const child = root ? slotOf(childKind, declaredEntry(parent, root), slot) : null;
+ if (!child) problems.push({ token: text, code: 'CONFIGURATION_AUTHORIZATION_UNKNOWN_ITEM' });
+ else if (!protectedSpec) problems.push({ token: text, code: 'CONFIGURATION_ADOPT_UNPROTECTED' });
+ else rowApprovals.add(`adopt:${childKind}:${encodeURIComponent(portKeyOf(parent, root))}/${encodeURIComponent(child)}`);
+ continue;
+ }
const kind = text.slice(0, text.indexOf(':'));
if (!has(TOKEN_FIELDS, kind)) { unclaimed.push(token); continue; }
- const [list, field] = TOKEN_ROOTS[kind];
const rest = text.slice(kind.length + 1);
- const roots = Array.isArray(spec && spec[list]) ? spec[list].filter(isObject).map((e) => e[field]).filter(nonEmptyString) : [];
+ const roots = declaredRoots(kind);
const exact = kind === 'duplicateRule';
const root = roots
.filter((name) => (exact ? rest.startsWith(`${name}:`) : lower(rest).startsWith(`${lower(name)}:`)))
@@ -2572,7 +2709,7 @@ function configurationAuthorizationKeys(tokens, spec) {
if (!TOKEN_FIELDS[kind].test(tail)) { problems.push({ token: text, code: 'CONFIGURATION_AUTHORIZATION_INVALID' }); continue; }
keys.add(`${kind}:${portKeyOf(kind, root)}:${tail}`);
}
- return { keys, problems, unclaimed };
+ return { keys, overwrite, rowApprovals, problems, unclaimed };
}
// The build runner's items for this feature: ONE data-model item and ONE solution-version item, whatever the
@@ -2743,15 +2880,34 @@ async function readConfigurationForDownload(sdk, entries) {
// Verify. Checks: {kind, key, name, ok, code?, fields?}; `name` is 'definition', 'binding', 'value',
// 'implementation', 'publication' or 'version'. A check never carries a value.
+// A typed stop's code as an exact port raised it: the lower-case codes of the binding store and the create identity
+// (`configuration-row-not-found`, `managed-settlement-pending`, `create-identity-unverified`) as well as the SDK's own.
+const TYPED_CODE = /^[a-z][a-z0-9-]{2,63}$/;
+const typedCodeOf = (error) => (error && typeof error.code === 'string' && TYPED_CODE.test(error.code) ? error.code : codeOf(error));
+
+// The row an exact port's binding names, read at that id; any other answer of the port is not a row to verify.
+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' };
+}
+
async function verifyKind(ctx, kindPlan, entries, checks, onFound) {
for (const entry of entries) {
const { kind } = kindPlan;
const key = kindPlan.key(entry);
+ // Under an exact port (protected configuration) verify asks only it: the row its binding holds, read at that id, or a
+ // typed reason there is none (lib/configuration-protected.js protectedVerifyPort). Never a name, and the reason is
+ // reported as the port gave it — a gone bound row is configuration-row-not-found, not a missing name.
+ const exactPort = exactPortOf(ctx, kind);
let found;
try {
- found = await locate({ ...ctx, managed: ctx.managed && { lookup: ctx.managed.lookup } }, kind, key, kindPlan.identity(entry));
+ found = exactPort
+ ? await locateExactly(ctx, exactPort, kind, key)
+ : await locate({ ...ctx, managed: ctx.managed && { lookup: ctx.managed.lookup } }, kind, key, kindPlan.identity(entry));
} catch (error) {
- checks.push({ kind, key, name: 'definition', ok: false, code: codeOf(error) });
+ checks.push({ kind, key, name: 'definition', ok: false, code: exactPort ? typedCodeOf(error) : codeOf(error) });
continue;
}
if (!found) { checks.push({ kind, key, name: 'definition', ok: false, code: 'NOT_FOUND' }); continue; }
@@ -2835,8 +2991,9 @@ function configurationTeardownNotes(spec) {
}
// ---- An injected stable-id create port, as this module would take it ----
-// Not used by the plugin in this release: the configuration kinds use the plain create path (defaultCreates), and no
-// stable-id module is part of the plugin. These adapters run only for a caller that injects the stable-id functions
+// Not used by the plugin in this release: without the protected opt-in the configuration kinds use the plain create path
+// (defaultCreates), and under it the protected port (configuration-protected.js); no injected stable-id module is part of
+// the plugin. These adapters run only for a caller that injects the stable-id functions
// itself (configurationContext `fence`: `intentFor`, `resolveProtectedTarget`, `createCreatesPortForSpec`), so this
// module loads none of them; configurationStableCreates (below) composes them into the configuration kinds' own port.
//
@@ -2924,7 +3081,8 @@ function configurationCreates(port, { resolveProtectedTarget, provision, spec, b
// forms, charts, ...) like their call sites, and these kinds are keyed here (portKeyOf, the value slot that only the
// deployment settings decide), so only this module can say what each create is. A build port that already protects
// every configuration kind AND resolves (configurationAcceptsPort) is used as is; any other is set aside, never half
-// used. The build's port in this release is the plain pass-through, which never qualifies.
+// used. The build's port in this release is the plain pass-through, which never qualifies; under the protected opt-in the
+// build hands this step the protected port (configuration-protected.js), which does.
//
// Every configuration kind is protected as a NEW feature declaration (the injected port's `featureKinds`), with or
// without the spec's `createIdentity` option: `shippedKinds` would leave them unprotected for a spec without the
@@ -2941,8 +3099,8 @@ const CONFIGURATION_CREATE_KINDS = Object.freeze(['environmentVariable', 'connec
const STANDALONE_SOLUTION = 'Default';
// The stable-id functions for one context: only the ones a caller injects (`ctx.fence`), never a module of the plugin.
-// The configuration kinds use the plain create path in this release, so nothing here loads a stable-id module; a
-// context without `fence` (every build and every standalone run) gets the plain pass-through (defaultCreates).
+// No injected stable-id module is part of the plugin, so nothing here loads one; a context without `fence` (every build
+// and every standalone run) gets the plain pass-through (defaultCreates) unless the build hands it the protected port.
const fenceOf = (ctx) => ctx.fence || null;
// Whether a port the build hands over can stand in for this module's own: it protects every configuration kind and
@@ -3013,6 +3171,9 @@ module.exports = {
configurationDestructive,
configurationHaltMessage,
configurationAuthorizationKeys,
+ // The `--authorize` flags spelled as one shell argument each (commandArgOrPlaceholder): the protected preflight's
+ // overwrite approval names a duplicate rule's key, which may hold white space or quotes.
+ authorizeFlags,
runConfigurationStep,
configurationBlocking,
configurationPlanItems,
@@ -3022,4 +3183,13 @@ module.exports = {
readConfigurationForDownload,
MEMBERSHIP_TABLES,
CHILD_MEMBERSHIP_TABLES,
+ CLASSIC_MEMBERSHIP_TYPES,
+ // The pure helpers the protected configuration driver (lib/configuration-create-bindings.js) derives its row plan
+ // from, so a planned row and the artifact the SDK pushes come from one definition.
+ buildArtifact,
+ describes,
+ normalCondition,
+ portableIntent,
+ portKeyOf,
+ ruleStatus,
};
diff --git a/plugins/model-apps/scripts/lib/configuration-build.js b/plugins/model-apps/scripts/lib/configuration-build.js
index 4100d2abe..ddd3dfa20 100644
--- a/plugins/model-apps/scripts/lib/configuration-build.js
+++ b/plugins/model-apps/scripts/lib/configuration-build.js
@@ -54,6 +54,25 @@ function namedByPages(pages) {
return { references, apis };
}
+// Every stop before the build's first write: the same plan stops again, so it is RETRY.NEVER.
+const preflightHalt = (preflightCode, message) => new BuildHalt(message, { phase: 'preflight', code: preflightCode, recoverable: false, retry: RETRY.NEVER });
+
+/**
+ * The binding store's own configuration debt (lib/configuration-protected.js pendingSweep, answered by the build's hookup
+ * `opts.protectedConfiguration.sweep`), read before the build's first service change: an attempt an earlier build left
+ * unfinished for an item this App Spec no longer declares stops the build here, with nothing sent. It runs whatever the
+ * App Spec declares — sdk-build.js calls it directly for an App Spec that uses no configuration kind, and the runtime's
+ * preflight calls it first otherwise — so omitting a declaration never bypasses its debt. No hookup, nothing to read.
+ */
+function sweepPendingConfiguration(spec, opts = {}) {
+ const sweep = opts.protectedConfiguration && opts.protectedConfiguration.sweep;
+ if (typeof sweep !== 'function') return { halts: [] };
+ const { halts } = sweep({ spec });
+ if (!halts.length) return { halts };
+ const others = halts.slice(1).map((h) => `${h.kind} ${h.key}`);
+ throw preflightHalt(halts[0].code, `${halts[0].kind} ${halts[0].key}: ${halts[0].message}${others.length ? ` Also held: ${others.join(', ')}.` : ''}`);
+}
+
/**
* @param {object} parts
* @param {object} parts.spec the App Spec (normalized, validated)
@@ -67,14 +86,25 @@ function namedByPages(pages) {
function createConfigurationRuntime({ spec, sdk, provision, opts = {}, appUniqueName } = {}) {
if (!spec || !sdk) throw new TypeError('createConfigurationRuntime: spec and sdk are required');
precomputeIntents(spec);
+ // Protected configuration (`configurationIdentity: "stable-v1"`) is loaded only when the App Spec opts in, so a build
+ // without the opt-in loads none of its modules and sends exactly what it sent before. Under the opt-in the build hands
+ // over its hookup (`opts.protectedConfiguration`, lib/configuration-protected.js createProtectedConfiguration over the
+ // build's binding store, send-once gate and managed create context); without it nothing protected can be proved, so the
+ // preflight stops the build before any write (create-identity-unverified) rather than fall back to name lookup.
+ const protectedOptIn = spec.configurationIdentity === 'stable-v1';
+ const hookup = protectedOptIn && opts.protectedConfiguration && typeof opts.protectedConfiguration.port === 'function' ? opts.protectedConfiguration : null;
+ // `sdk` is the workspace the build reads protected rows into: the preflight refuses to read over a local copy with edits.
+ const protectedArgs = () => ({ spec, dataverse: sdk.dataverse, solution: spec.solution && spec.solution.uniqueName, bindings: opts.configurationBindings, sdk });
+ const protectedPort = hookup ? hookup.port(protectedArgs()) : null;
const ctx = C.configurationContext({
sdk,
// The build's create port only when it can stand in for the configuration kinds' own (it protects every one of
// them and resolves: C.configurationAcceptsPort). The build's port protects the kinds of its own catalog or none
// (the plain pass-through), and half using it would send these creates under random ids; otherwise the helper
- // uses its default, the plain pass-through (lib/creates-passthrough.js): the configuration kinds load no
- // stable-id module in this release. Ordinary creation never depends on a port being supplied.
- creates: C.configurationAcceptsPort(opts.creates) ? opts.creates : undefined,
+ // uses its default, the plain pass-through (lib/creates-passthrough.js): without the protected opt-in the
+ // configuration kinds load no stable-id module. Ordinary creation never depends on a port being supplied. Under the
+ // protected opt-in the port is the protected one, always: exact ids from the binding store, never a name.
+ creates: protectedPort || (C.configurationAcceptsPort(opts.creates) ? opts.creates : undefined),
managed: opts.managed,
bindings: opts.configurationBindings,
solutionUniqueName: spec.solution && spec.solution.uniqueName,
@@ -119,6 +149,42 @@ function createConfigurationRuntime({ spec, sdk, provision, opts = {}, appUnique
return {
ctx,
+ // The protected configuration's whole-plan, read-only preflight (lib/configuration-protected.js), run by the build
+ // before its first write — the solution, its version, a table, a variable. Without the opt-in it reads only the binding
+ // store the build handed over, if any (nothing is sent). Under it, an item the binding store cannot locate exactly, or an edit the protected path cannot
+ // make, stops the build here with nothing sent; every such stop is RETRY.NEVER, as the same plan stops again.
+ async preflight() {
+ const fail = preflightHalt;
+ // The store's own debt first, whatever this App Spec still declares (sweepPendingConfiguration).
+ sweepPendingConfiguration(spec, opts);
+ if (!protectedOptIn) {
+ // Removing the opt-in is not a migration: a declared item the build's binding store still holds (committed, or an
+ // attempt pending) would go back to name lookup, where a namesake could stand in for its bound row. A local store
+ // read only, and only when the build handed its hookup over; an App Spec that never opted in has nothing there.
+ // The hookup answers it itself (createProtectedConfiguration obligations), so a default build never requires the
+ // protected modules from here.
+ const obligations = opts.protectedConfiguration && opts.protectedConfiguration.obligations;
+ if (typeof obligations !== 'function') return { halts: [] };
+ const { halts } = obligations({ spec });
+ if (!halts.length) return { halts };
+ const others = halts.slice(1).map((h) => `${h.kind} ${h.key}`);
+ throw fail(halts[0].code, `${halts[0].kind} ${halts[0].key}: ${halts[0].message}${others.length ? ` Also held: ${others.join(', ')}.` : ''}`);
+ }
+ if (!hookup) {
+ throw fail('create-identity-unverified', 'configurationIdentity "stable-v1" needs the binding store for protected configuration, and it is not available to this build. No service changes were sent by this build.');
+ }
+ // The maker's overwrite approvals reach only the preflight: the one step that may replace a protected item's local copy.
+ const { halts } = await hookup.preflight({ ...protectedArgs(), authorizedOverwrite: opts.authorizedOverwrite });
+ if (!halts.length) return { halts };
+ // The edit refusal leads when there is one: it is the halt a maker acts on first, and its text is fixed.
+ const first = halts.find((h) => h.code === 'configuration-edit-unsupported') || halts[0];
+ const others = halts.filter((h) => h !== first).map((h) => `${h.kind} ${h.key} (${h.code})`);
+ // A row of an earlier, unfinished create that no answer proved this build's own is adopted only under the maker's
+ // exact approval token, one per row (managed-create-context.js judgeRows), never wholesale.
+ const approvals = [...new Set(halts.flatMap((h) => h.approvals || []))];
+ const approve = approvals.length ? ` Its rows are bound only under these exact approvals, given after checking those rows are yours: ${approvals.map((t) => JSON.stringify(t)).join(', ')}.` : '';
+ throw fail(first.code, `${first.kind} ${first.key}: ${first.message}${others.length ? ` Also stopped: ${others.join(', ')}.` : ''}${approve}`);
+ },
// Plan, apply and observe ONE phase's items. Returns {outcome, blocking, halt, plan}.
async apply(phase) {
if (phase !== 'solution' && phase !== 'data-model') throw new TypeError(`configuration runtime: unknown phase ${phase}`);
@@ -172,4 +238,4 @@ function createConfigurationRuntime({ spec, sdk, provision, opts = {}, appUnique
};
}
-module.exports = { createConfigurationRuntime };
+module.exports = { createConfigurationRuntime, sweepPendingConfiguration };
diff --git a/plugins/model-apps/scripts/lib/configuration-create-bindings.js b/plugins/model-apps/scripts/lib/configuration-create-bindings.js
new file mode 100644
index 000000000..b35712997
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/configuration-create-bindings.js
@@ -0,0 +1,1452 @@
+'use strict';
+
+// The protected create driver of the four configuration families — environment variables, connection references,
+// Custom APIs and duplicate detection rules — over the managed create lifecycle (managed-create-context.js) and its
+// send-once gate (managed-create-transport.js). The build uses it under the `configurationIdentity` opt-in, through the
+// protected port (configuration-protected.js); this module answers the questions a protected create must ask, and
+// nothing here sends a write.
+// planOf(spec, opts) the row plan of one artifact (buildRowPlan input) at its derived ids
+// createClassifier(entries) the gate's classifier: which planned row (or completion effect) a request is
+// classifyConstituent(entries, req) the same, for one constituent of a $batch change set (a bound Custom API's edit)
+// readConfigurationRow(dv, kind, id) one exact-id read: present (with its row version), absent (only a 404 0x80040217) or unknown
+// readConfigurationConflicts(dv, p) the fully paged namesake queries a create must run first
+// observe(dv, planned) the fresh read a recovery or a settle judges, the root's complete child graph included
+// readComponentTypes(dv) the ObjectTypeCode of each member table
+// acceptResultFor(planned) the run's check of what the SDK's pushArtifact answered
+//
+// Why the comparisons are closed tables rather than "compare what came back":
+// - A row at the derived id is ours only when it holds exactly what the plan prepared. Every column a read selects
+// decodes through a fixed table; a value the table does not know (a new option code, a type change) is UNKNOWN,
+// never "close enough", and a column this build never writes must be empty or the row is not the one it prepared.
+// - The projection a row is judged by hashes semantic fields (names exact, table and column names lower case), so the
+// same row read through another API version or spelling compares the same. A Custom API's labels the App Spec leaves
+// out are pinned in the plan to what the SDK fills them with (pinApiLabels), so any other label is a difference.
+// - A private input — an environment variable's value, a connection reference's connection id — is never part of a
+// plan, a projection, a sealed send or a hash: it is held in memory against the planned object only (PRIVATE), and
+// compared there. Even its digest would be a dictionary-attackable copy of a short secret, so none is kept.
+
+const crypto = require('crypto');
+const { canonicalJson, normalizeGuid } = require('./reconcile-common.js');
+const { odataLit } = require('./odata.js');
+const { isRestrictedSolution } = require('./system-solutions.js');
+const { apiPath, headerValue } = require('./workflow-effect-context.js');
+const { sentProjection } = require('./managed-create-transport.js');
+const { CODES, acceptSaved } = require('./managed-create-context.js');
+const { intentFor: defaultIntentFor } = require('./creates-capabilities.js');
+const { createIntentCatalog } = require('./creates-port.js');
+const A = require('./configuration-artifacts.js');
+
+// The binding store's not-found code for a bound row that is gone, and the delete refusal of this driver's scope.
+const NOT_FOUND_CODE = 'configuration-row-not-found';
+const DELETE_CODE = 'configuration-protected-removal-unsupported';
+const PRIVATE_MISMATCH = 'configuration-private-input-mismatch';
+
+const sha = (value) => crypto.createHash('sha256').update(canonicalJson(value), 'utf8').digest('hex');
+const lower = (v) => String(v).toLowerCase();
+const isPlain = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
+const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
+const nonEmpty = (v) => typeof v === 'string' && v.trim() !== '';
+const rowKey = (kind, key) => `${kind}\u0000${key}`;
+
+// ---------------------------------------------------------------------------------------------
+// Closed option tables. A code outside a table decodes to BAD: the row is unreadable, never matched.
+
+// environmentvariabledefinition.type
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/environmentvariabledefinition#BKMK_Type
+const EV_TYPES = Object.freeze({ string: 100000000, number: 100000001, boolean: 100000002, json: 100000003, dataSource: 100000004, secret: 100000005 });
+// environmentvariabledefinition.secretstore: where a Secret's value is kept. The SDK manages a Secret only as an Azure
+// Key Vault reference and refuses to fetch one whose secretstore is set to anything but 0
+// (ENVIRONMENT_VARIABLE_SECRET_UNRECOGNIZED). No create this build plans sends the column, whatever the type, so a row it
+// made reads back empty or 0 (the column's default); 1 (kept by Dataverse) is a definition someone else made or changed,
+// and a code outside the table is unreadable.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/environmentvariabledefinition#BKMK_SecretStore
+const SECRET_STORES = Object.freeze({ keyVault: 0, dataverse: 1 });
+// customapi.bindingtype and customapi.allowedcustomprocessingsteptype
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/customapi#BKMK_BindingType
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/customapi#BKMK_AllowedCustomProcessingStepType
+const API_BINDINGS = Object.freeze({ global: 0, entity: 1, entityCollection: 2 });
+const API_STEPS = Object.freeze({ none: 0, asyncOnly: 1, syncAndAsync: 2 });
+// customapirequestparameter.type and customapiresponseproperty.type (one option set)
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/customapirequestparameter#BKMK_Type
+const PARAM_TYPES = Object.freeze({
+ boolean: 0, dateTime: 1, decimal: 2, entity: 3, entityCollection: 4, entityReference: 5, float: 6, integer: 7,
+ money: 8, picklist: 9, string: 10, stringArray: 11, guid: 12,
+});
+// duplicaterulecondition.operatorcode; operatorparam carries the character count of first/lastCharacters.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/duplicaterulecondition#BKMK_OperatorCode
+const MATCH_CODES = Object.freeze({ exact: 0, firstCharacters: 1, lastCharacters: 2, sameDate: 3, sameDateAndTime: 4, exactChoiceLabel: 5, exactChoiceValue: 6 });
+// duplicaterule statecode/statuscode: 0/0 Unpublished, 0/1 Publishing (a job in flight: neither state), 1/2 Published.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/duplicaterule#BKMK_StatusCode
+function ruleStateOf(statecode, statuscode) {
+ if (statecode === 0 && statuscode === 0) return 'unpublished';
+ if (statecode === 1 && statuscode === 2) return 'published';
+ return undefined;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Decoders: wire value -> semantic value, or BAD.
+
+const BAD = Symbol('bad');
+const text = (v) => (v === null || typeof v === 'string' ? v : BAD);
+const lowerText = (v) => (v === null ? null : typeof v === 'string' ? v.toLowerCase() : BAD);
+const bool = (v) => (typeof v === 'boolean' ? v : BAD);
+const guid = (v) => (v === null ? null : typeof v === 'string' && normalizeGuid(v) ? normalizeGuid(v) : BAD);
+const count = (v) => (v === null || (Number.isInteger(v) && v >= 0) ? v : BAD);
+function code(table) {
+ const byCode = new Map(Object.entries(table).map(([name, n]) => [n, name]));
+ return (v) => (byCode.has(v) ? byCode.get(v) : BAD);
+}
+// An optional choice column: empty, or a code of its table.
+function optionalCode(table) {
+ const decodeCode = code(table);
+ return (v) => (v === null ? null : decodeCode(v));
+}
+// A column this build never writes. It may only be empty: a value there was put by someone else.
+const UNMODELLED = 'unmodelled';
+// A column this build never writes that the platform fills on create with a known default, and that may be changed
+// outside the plugin once the row exists. Dataverse stores 0 in a connection reference's `promptingbehavior` when the
+// create omits it (a live read shows `"promptingbehavior": 0` on every reference the build made), so a closed map that
+// expected it empty never proved one; a maker can later set it in the portal.
+// - A body that carries the column at all, an explicit null included, is unmodelled: no request this build planned
+// writes it, and a null would clear what the platform or a maker put there.
+// - A read that finds it empty or holding exactly the default reports nothing: the two are the same platform state.
+// - A read that finds any other value keeps it as preserved bound-row state (decoded.preserved), as PRESERVED below: a
+// create expects none, so a fresh row holding it is still a conflict; an update expects exactly what its fresh base
+// read held (planOf), so an edit of a row changed outside the plugin is planned over that value, never writes it,
+// and is proved only while the row still holds it.
+const defaulted = (value) => Object.freeze({ defaulted: value });
+const isDefaulted = (spec) => isPlain(spec) && has(spec, 'defaulted');
+// A column this build never writes but a BOUND row may hold, set outside the plugin: a Custom API's implementation (its
+// plug-in type), which an App Spec cannot declare (configuration-artifacts.js refuses `pluginTypeId`) and which is
+// registered after the API exists. A read keeps its exact value (decoded.preserved); a body that carries the column at all
+// is not a write this build planned. A create expects it empty, as an unmodelled column; an update expects exactly the
+// value its fresh base read held (planOf), so an edit is proved only while the row still holds that same implementation.
+const PRESERVED = 'preserved';
+// The private input's column: compared in memory (privateStateOf), never projected.
+const PRIVATE = 'private';
+// The lookup to the row's parent: the managed row protocol's parentId (managed-create-context.js), not a field.
+const PARENT = 'parent';
+// The rule's state columns: read as ruleState (observe), not a field.
+const STATE = 'state';
+
+// Each kind: its entity set, primary key, the table its component type is read from, the namesake column (roots), the
+// parent's set and lookup (children), and the closed map of every column a read selects and a create may send:
+// column -> [semantic field, decoder, create default when the body omits it] or one of the markers above.
+// A create default is what the platform stores for an omitted column (null text, false flags, the first option); a
+// required column has none, so a body without it is not the planned create.
+// Column names: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/about-entity-reference
+const KINDS = Object.freeze({
+ environmentVariable: {
+ set: 'environmentvariabledefinitions', pk: 'environmentvariabledefinitionid', name: 'schemaname', nameField: 'schemaName',
+ columns: {
+ schemaname: ['schemaName', text], displayname: ['name', text, null], description: ['description', text, null],
+ type: ['type', code(EV_TYPES)], defaultvalue: ['defaultValue', text, null], isrequired: ['isRequired', bool, false],
+ valueschema: ['valueSchema', text, null], apiid: ['connectorId', text, null], parameterkey: ['parameterKey', text, null],
+ _parentdefinitionid_value: ['parentDefinitionId', guid, null], secretstore: ['secretStore', optionalCode(SECRET_STORES), null],
+ hint: UNMODELLED, learnmoreurl: UNMODELLED, inputcontrolconfig: UNMODELLED,
+ },
+ binds: { ParentDefinitionId: ['_parentdefinitionid_value', 'environmentvariabledefinitions'] },
+ },
+ // A value row is never a solution member (it would export this environment's value), and it carries nothing but
+ // the private value and its definition.
+ environmentVariableValue: {
+ set: 'environmentvariablevalues', pk: 'environmentvariablevalueid', parentSet: 'environmentvariabledefinitions',
+ parentBind: 'EnvironmentVariableDefinitionId', parentColumn: '_environmentvariabledefinitionid_value', nav: null,
+ columns: { value: PRIVATE, _environmentvariabledefinitionid_value: PARENT },
+ privateColumn: 'value',
+ },
+ connectionReference: {
+ set: 'connectionreferences', pk: 'connectionreferenceid', name: 'connectionreferencelogicalname', nameField: 'logicalName',
+ columns: {
+ connectionreferencelogicalname: ['logicalName', text], connectionreferencedisplayname: ['name', text, null],
+ description: ['description', text, null], connectorid: ['connectorId', text], _customconnectorid_value: ['customConnectorId', guid, null],
+ connectionid: PRIVATE,
+ connectionparametersconfig: UNMODELLED, connectionparametersetconfig: UNMODELLED, promptingbehavior: defaulted(0),
+ },
+ binds: { CustomConnectorId: ['_customconnectorid_value', 'connectors'] },
+ privateColumn: 'connectionid',
+ },
+ customApi: {
+ set: 'customapis', pk: 'customapiid', name: 'uniquename', nameField: 'uniqueName',
+ columns: {
+ uniquename: ['uniqueName', text], name: ['name', text, null], displayname: ['displayName', text, null], description: ['description', text, null],
+ bindingtype: ['binding', code(API_BINDINGS), 'global'], boundentitylogicalname: ['boundEntityLogicalName', lowerText, null],
+ isfunction: ['isFunction', bool, false], isprivate: ['isPrivate', bool, false],
+ allowedcustomprocessingsteptype: ['allowedProcessingSteps', code(API_STEPS), 'none'], workflowsdkstepenabled: ['enabledForWorkflow', bool, false],
+ executeprivilegename: ['executePrivilegeName', text, null],
+ _plugintypeid_value: PRESERVED,
+ },
+ binds: {},
+ },
+ customApiRequestParameter: {
+ set: 'customapirequestparameters', pk: 'customapirequestparameterid', parentSet: 'customapis',
+ parentBind: 'CustomAPIId', parentColumn: '_customapiid_value', nav: 'CustomAPIRequestParameters',
+ columns: {
+ uniquename: ['uniqueName', text], name: ['name', text, null], displayname: ['displayName', text, null], description: ['description', text, null],
+ type: ['type', code(PARAM_TYPES)], logicalentityname: ['entityLogicalName', lowerText, null], isoptional: ['isOptional', bool, false],
+ _customapiid_value: PARENT,
+ },
+ },
+ customApiResponseProperty: {
+ set: 'customapiresponseproperties', pk: 'customapiresponsepropertyid', parentSet: 'customapis',
+ parentBind: 'CustomAPIId', parentColumn: '_customapiid_value', nav: 'CustomAPIResponseProperties',
+ columns: {
+ uniquename: ['uniqueName', text], name: ['name', text, null], displayname: ['displayName', text, null], description: ['description', text, null],
+ type: ['type', code(PARAM_TYPES)], logicalentityname: ['entityLogicalName', lowerText, null],
+ _customapiid_value: PARENT,
+ },
+ },
+ duplicateRule: {
+ set: 'duplicaterules', pk: 'duplicateruleid', name: 'name', nameField: 'name',
+ columns: {
+ name: ['name', text], description: ['description', text, null], baseentityname: ['entityLogicalName', lowerText],
+ matchingentityname: ['matchingEntityLogicalName', lowerText], iscasesensitive: ['caseSensitive', bool, false],
+ excludeinactiverecords: ['excludeInactiveRecords', bool, false], statecode: STATE, statuscode: STATE,
+ },
+ binds: {},
+ },
+ // A condition is only ever created inside its rule's deep insert: a condition sent on its own (a direct POST or the
+ // platform's CompoundUpdateDuplicateDetectionRule $batch) is refused, so its parent is never bound by a body.
+ duplicateRuleCondition: {
+ set: 'duplicateruleconditions', pk: 'duplicateruleconditionid', parentSet: 'duplicaterules',
+ parentBind: null, parentColumn: '_regardingobjectid_value', nav: 'DuplicateRule_DuplicateRuleConditions',
+ columns: {
+ baseattributename: ['column', lowerText], matchingattributename: ['matchingColumn', lowerText, null],
+ operatorcode: ['match', code(MATCH_CODES)], operatorparam: ['characters', count, null], ignoreblankvalues: ['ignoreBlankValues', bool, false],
+ _regardingobjectid_value: PARENT,
+ },
+ },
+});
+const ROOT_KINDS = new Set(['environmentVariable', 'connectionReference', 'customApi', 'duplicateRule']);
+// The slot of a child under its root, as the create port names it (configurationCreateIntents).
+function childKindOf(rootKind, slot) {
+ if (rootKind === 'environmentVariable') return 'environmentVariableValue';
+ if (rootKind === 'customApi') return slot.startsWith('request:') ? 'customApiRequestParameter' : 'customApiResponseProperty';
+ return 'duplicateRuleCondition';
+}
+// The membership component type of each kind: a table's ObjectTypeCode, read at plan time (readComponentTypes); an
+// environment variable definition's is the fixed 380.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/solutioncomponent#BKMK_ComponentType
+const MEMBER_TABLES = Object.freeze({ ...A.MEMBERSHIP_TABLES, ...A.CHILD_MEMBERSHIP_TABLES });
+
+// ---------------------------------------------------------------------------------------------
+// Decoding and projection
+
+// A lookup in a body: "[email protected]": "/environmentvariabledefinitions(<guid>)". Only the
+// set the kind binds to, by GUID; an alternate key or another set names no row this plan prepared.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/associate-disassociate-entities-using-web-api#associate-entity-records-on-create
+function boundGuid(value, set) {
+ const m = /^\/?([A-Za-z_][A-Za-z0-9_]*)\(([^()]*)\)$/.exec(typeof value === 'string' ? value : '');
+ if (!m || m[1].toLowerCase() !== set) return BAD;
+ return normalizeGuid(m[2]) || BAD;
+}
+
+/**
+ * Decode one wire object of `kind` through its closed map. `mode`:
+ * 'read' a row a read selected every mapped column of: a missing column is unreadable;
+ * 'create' a create body: an omitted column takes its create default, an omitted required column is not the plan;
+ * 'patch' a PATCH body: only what it carries.
+ * Answers { fields, unmodelled, preserved, parentId, private: { present, value }, state } or null (unreadable / not this
+ * kind's); `preserved` maps each filled PRESERVED column to its GUID and each defaulted column holding another value than
+ * its default to that value, and only a read has any.
+ * A body's keys outside the map (other than the primary key, an allowed bind and the navigations the caller takes
+ * out) make it null: a column this build does not model is not part of any create it planned.
+ */
+function decode(kind, raw, mode) {
+ if (!isPlain(raw)) return null;
+ const k = KINDS[kind];
+ const wire = {};
+ let parentId;
+ for (const [key, value] of Object.entries(raw)) {
+ if (key === k.pk) continue;
+ if (mode === 'read' && key.startsWith('@odata.')) continue;
+ const bind = /^(.+)@odata\.bind$/.exec(key);
+ if (bind && mode !== 'read') {
+ if (k.parentBind && bind[1] === k.parentBind) {
+ const g = boundGuid(value, k.parentSet);
+ if (g === BAD) return null;
+ parentId = g;
+ continue;
+ }
+ const target = k.binds && k.binds[bind[1]];
+ if (!target) return null;
+ const g = value === null ? null : boundGuid(value, target[1]);
+ if (g === BAD) return null;
+ wire[target[0]] = g;
+ continue;
+ }
+ if (!has(k.columns, key)) {
+ if (mode === 'read') continue;
+ return null;
+ }
+ wire[key] = value;
+ }
+ const fields = {};
+ const unmodelled = [];
+ const preserved = {};
+ const state = {};
+ let secret = { present: false, value: undefined };
+ for (const [col, spec] of Object.entries(k.columns)) {
+ const present = has(wire, col);
+ const v = wire[col];
+ if (spec === UNMODELLED) { if (present && v !== null) unmodelled.push(col); continue; }
+ if (isDefaulted(spec)) {
+ if (!present) continue;
+ if (mode !== 'read') { unmodelled.push(col); continue; }
+ if (v === null || v === spec.defaulted) continue;
+ // The only values a preserved column holds are JSON scalars a projection can hash; anything else is unreadable.
+ if (typeof v !== 'number' && typeof v !== 'string' && typeof v !== 'boolean') return null;
+ preserved[col] = v;
+ continue;
+ }
+ if (spec === PRESERVED) {
+ if (!present) continue;
+ // Never written: even an explicit null would clear the implementation someone else registered.
+ if (mode !== 'read') return null;
+ if (v === null) continue;
+ const g = guid(v);
+ if (g === BAD) return null;
+ preserved[col] = g;
+ continue;
+ }
+ if (spec === PRIVATE) { if (present) secret = { present: true, value: v }; continue; }
+ if (spec === STATE) { if (present) state[col] = v; else if (mode === 'read') return null; continue; }
+ if (spec === PARENT) {
+ if (!present) { if (mode === 'read') return null; continue; }
+ const g = guid(v);
+ if (g === BAD || (parentId !== undefined && parentId !== g)) return null;
+ parentId = g;
+ continue;
+ }
+ const [field, decoder, fallback] = spec;
+ if (!present) {
+ if (mode === 'patch') continue;
+ if (mode === 'create' && spec.length === 3) { fields[field] = fallback; continue; }
+ return null;
+ }
+ const d = decoder(v);
+ if (d === BAD) return null;
+ fields[field] = d;
+ }
+ return { fields, unmodelled: unmodelled.sort(), preserved, parentId: parentId === undefined ? undefined : parentId, private: secret, state };
+}
+
+// The semantic fields a decoded row compares by. A condition takes the comparable shape the planner uses
+// (normalCondition: its matching column defaults to its own column, a character count only where it counts); a
+// connection reference says only WHETHER it is connected — which connection is private.
+function semanticOf(kind, decoded, mode = 'read') {
+ if (kind === 'duplicateRuleCondition') {
+ if (mode === 'patch') return decoded.fields;
+ return A.normalCondition(decoded.fields);
+ }
+ if (kind === 'connectionReference' && (mode !== 'patch' || decoded.private.present)) {
+ const v = decoded.private.value;
+ return { ...decoded.fields, connected: decoded.private.present && v !== null && v !== undefined && v !== '' };
+ }
+ // Empty and 0 (Key Vault, the default) are the one store a definition this build made can read back with (SECRET_STORES).
+ if (kind === 'environmentVariable' && has(decoded.fields, 'secretStore')) {
+ return { ...decoded.fields, secretStore: decoded.fields.secretStore === 'keyVault' ? null : decoded.fields.secretStore };
+ }
+ return decoded.fields;
+}
+
+const LABELS = ['name', 'displayName', 'description'];
+const labelsOf = (from) => Object.fromEntries(LABELS.map((f) => [f, has(from, f) && from[f] !== undefined ? from[f] : null]));
+const guidOrText = (v) => (v == null ? null : normalizeGuid(v) || String(v));
+
+// What a row the plan prepares must read back as, from the artifact the SDK is handed (configuration-artifacts.js
+// buildArtifact) — one definition for both, so the plan and the push cannot drift apart. A Custom API's labels are
+// all in it: planOf pins the ones the App Spec leaves out (pinApiLabels) before this reads them.
+function expectedOf(kind, artifact, child) {
+ switch (kind) {
+ case 'environmentVariable':
+ return {
+ schemaName: artifact.schemaName, name: artifact.name, description: artifact.description, type: artifact.type,
+ defaultValue: artifact.defaultValue, isRequired: artifact.isRequired, valueSchema: artifact.valueSchema,
+ connectorId: artifact.connectorId, parameterKey: artifact.parameterKey, parentDefinitionId: artifact.parentId ? normalizeGuid(artifact.parentId) : null,
+ secretStore: null,
+ };
+ case 'environmentVariableValue':
+ return {};
+ case 'connectionReference':
+ return {
+ logicalName: artifact.logicalName, name: artifact.name, description: artifact.description, connectorId: artifact.connectorId,
+ customConnectorId: guidOrText(artifact.customConnectorId), connected: artifact.connectionId != null && artifact.connectionId !== '',
+ };
+ case 'customApi':
+ return {
+ uniqueName: artifact.uniqueName, binding: artifact.binding, boundEntityLogicalName: artifact.boundEntityLogicalName,
+ isFunction: artifact.isFunction, allowedProcessingSteps: artifact.allowedProcessingSteps, enabledForWorkflow: artifact.enabledForWorkflow,
+ isPrivate: artifact.isPrivate, executePrivilegeName: artifact.executePrivilegeName, ...labelsOf(artifact),
+ };
+ case 'customApiRequestParameter':
+ case 'customApiResponseProperty':
+ return {
+ uniqueName: child.uniqueName, type: child.type, entityLogicalName: child.entityLogicalName == null ? null : lower(child.entityLogicalName),
+ ...(kind === 'customApiRequestParameter' ? { isOptional: child.isOptional === true } : {}), ...labelsOf(child),
+ };
+ case 'duplicateRule':
+ return {
+ name: artifact.name, description: artifact.description, entityLogicalName: artifact.entityLogicalName,
+ matchingEntityLogicalName: artifact.matchingEntityLogicalName, caseSensitive: artifact.caseSensitive, excludeInactiveRecords: artifact.excludeInactiveRecords,
+ };
+ case 'duplicateRuleCondition':
+ return A.normalCondition(child);
+ default:
+ throw new TypeError(`unsupported configuration kind ${kind}`);
+ }
+}
+
+// Whether the App Spec authors `field` on `from`: present and not undefined. An explicit null or false is authored (it
+// clears or turns off); only an omitted field is left to the row.
+const authored = (from, field) => isPlain(from) && has(from, field) && from[field] !== undefined;
+
+/**
+ * What a row the plan UPDATES must read back as: the row's own fields from its fresh exact read (`base`), with only what
+ * the App Spec authors laid over them — the same overlay the existing typed planner compares by
+ * (configuration-artifacts.js variablePlan, referencePlan, customApiPlan / compareChildren, duplicateRulePlan /
+ * overlayCondition). `created` is what a CREATE of the same declaration reads back as (expectedOf): an authored field
+ * takes its value from there, so a create and an update of one declaration say the same thing about it. An omitted
+ * field never takes a create default: the update does not send it, and the row keeps what it has.
+ * Kept from `created` in every case: the identity fields, the immutable ones the App Spec must state (a definition's
+ * type, a reference's connector, a rule's table, a child's type), a definition's secret store (only the store a create
+ * makes is supported, so another one read back is a difference, never an expectation) and a Custom API root's labels
+ * (pinApiLabels has already laid them over the base).
+ */
+function boundExpectation(kind, created, base, declared, binds) {
+ const row = semanticOf(kind, base.decoded);
+ const out = { ...created };
+ const keep = (field) => { out[field] = has(row, field) ? row[field] : null; };
+ const unless = (isAuthored, fields) => { if (!isAuthored) for (const f of fields) keep(f); };
+ switch (kind) {
+ case 'environmentVariable':
+ unless(declared.name != null, ['name']);
+ for (const f of ['description', 'defaultValue', 'valueSchema', 'connectorId', 'parameterKey']) unless(authored(declared, f), [f]);
+ unless(has(declared, 'isRequired'), ['isRequired']);
+ unless(has(declared, 'parentSchemaName'), ['parentDefinitionId']);
+ return out;
+ case 'connectionReference':
+ unless(declared.name != null, ['name']);
+ unless(authored(declared, 'description'), ['description']);
+ unless(authored(declared, 'customConnectorId'), ['customConnectorId']);
+ // Connected is what the deployment settings ask for when they name the reference, else the row's own.
+ unless(!!binds.connectionReferences.get(lower(declared.logicalName)), ['connected']);
+ return out;
+ case 'customApi':
+ for (const f of ['binding', 'boundEntityLogicalName', 'isFunction', 'allowedProcessingSteps', 'enabledForWorkflow', 'isPrivate', 'executePrivilegeName']) unless(authored(declared, f), [f]);
+ return out;
+ case 'customApiRequestParameter':
+ case 'customApiResponseProperty':
+ if (kind === 'customApiRequestParameter') unless(has(declared, 'isOptional'), ['isOptional']);
+ unless(authored(declared, 'entityLogicalName'), ['entityLogicalName']);
+ // A child's label: authored (an explicit null clears it) or the row's own.
+ for (const f of LABELS) out[f] = authored(declared, f) ? declared[f] : has(row, f) ? row[f] : null;
+ return out;
+ case 'duplicateRule':
+ unless(nonEmpty(declared.name), ['name']);
+ for (const f of ['description', 'matchingEntity', 'caseSensitive', 'excludeInactiveRecords']) unless(authored(declared, f), [f === 'matchingEntity' ? 'matchingEntityLogicalName' : f]);
+ return out;
+ case 'duplicateRuleCondition': {
+ // configuration-artifacts.js overlayCondition: the column and match are the declaration's; the matching column,
+ // character count and blank handling it omits stay as the row has them.
+ const fields = base.decoded.fields;
+ const pick = (f) => (authored(declared, f) ? declared[f] : fields[f]);
+ return A.normalCondition({ column: declared.column, matchingColumn: pick('matchingColumn'), match: declared.match, characters: pick('characters'), ignoreBlankValues: pick('ignoreBlankValues') === true });
+ }
+ default:
+ return out;
+ }
+}
+
+// The declaration of the child in `slot` of a root entry: a Custom API child by its unique name in its direction, a
+// condition by its key; a value has none (an empty object).
+function declaredChild(entry, slot) {
+ if (slot.startsWith('request:') || slot.startsWith('response:')) {
+ const list = slot.startsWith('request:') ? entry.requestParameters : entry.responseProperties;
+ return (list || []).find((c) => lower(c.uniqueName) === slot.slice(slot.indexOf(':') + 1)) || {};
+ }
+ return (entry.conditions || []).find((c) => c.key === slot) || {};
+}
+
+// The state a bound rule keeps when its App Spec omits `status`: the row's own, published while a publish is in flight.
+function boundRuleState(base) {
+ return ruleStateOf(base.decoded.state.statecode, base.decoded.state.statuscode) || 'published';
+}
+
+// The projection a row is judged by: the expected fields only, plus every unmodelled column a read found filled, every
+// preserved column's exact value and, for a root, every child row its complete graph holds that the plan does not (observe):
+// sha256(canonicalJson({ kind, fields: { <expected field>: <value>, ... }, unmodelled?: [<column>, ...],
+// preserved?: { <column>: <guid> }, unexpectedChildren?: ['<kind>:<id>', ...] }))
+// Each list or map is left out when empty, so a row with none hashes exactly as its expectation does. An expectation
+// carries `preserved` only for an update whose base read held one (planOf): a created row expects none.
+function projectionOf(kind, expected, semantic, unmodelled = [], unexpectedChildren = [], preserved = {}) {
+ const fields = Object.fromEntries(Object.keys(expected).map((f) => [f, has(semantic, f) ? semantic[f] : null]));
+ return sha({ kind, fields, ...(unmodelled.length ? { unmodelled } : {}), ...(Object.keys(preserved).length ? { preserved } : {}), ...(unexpectedChildren.length ? { unexpectedChildren } : {}) });
+}
+const sameValue = (a, b) => canonicalJson(a === undefined ? null : a) === canonicalJson(b === undefined ? null : b);
+
+// ---------------------------------------------------------------------------------------------
+// The plan
+
+// planned object -> { artifact, secrets: Map(rowKey -> private input) }. Module-private and keyed by the frozen planned
+// object, so a private input reaches no plan, no JSON of a planned object, no store record and no log: only the SDK
+// artifact (artifactFor) and the in-memory comparisons below see it.
+const PRIVATE_INPUTS = new WeakMap();
+const PLAN_KEY_FIELD = Object.freeze({ environmentVariable: 'schemaName', connectionReference: 'logicalName', customApi: 'uniqueName', duplicateRule: 'key' });
+
+// A Dataverse row version as a read answers it in `@odata.etag` and a conditional PATCH sends it in If-Match: W/"<n>".
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/perform-conditional-operations-using-web-api
+const ROW_VERSION = /^W\/"\d+"$/;
+
+// The fresh base read of one row a plan UPDATES: a readConfigurationRow answer, present, of that kind at that id, under
+// the planned parent and, for a kind a plan can PATCH, with a row version. Anything else throws: an update prepared from
+// no read, a stale read of another row or a PATCH-able read without a version would let a PATCH through with no
+// condition the plan holds. A duplicate rule and its conditions are never PATCHed under the opt-in (a changed rule stops
+// with configuration-edit-unsupported), so a bound rule is planned and verified by its exact id and content projection
+// alone — and Dataverse answers `duplicaterules` rows without `@odata.etag`, so requiring one there left a bound rule
+// that could never be rebuilt or verified.
+function baseOf(bases, kind, id, parentId) {
+ const b = bases instanceof Map ? bases.get(id) : isPlain(bases) && has(bases, id) ? bases[id] : undefined;
+ const versioned = !PATCHABLE.has(kind) || (isPlain(b) && typeof b.rowVersion === 'string' && ROW_VERSION.test(b.rowVersion));
+ if (!isPlain(b) || b.state !== 'present' || b.kind !== kind || b.id !== id || !versioned
+ || (parentId !== null && b.parentId !== parentId) || !isPlain(b.decoded) || !isPlain(b.decoded.fields)) {
+ throw new TypeError(`planOf: the ${kind} ${id} is planned as an update but has no fresh base read${PATCHABLE.has(kind) ? ' with a row version' : ''} (readConfigurationRow)`);
+ }
+ return b;
+}
+
+// Pin every Custom API label in the artifact before anything is planned from it, so the plan, the push and the read-back
+// all compare one value and no label is left for something else to fill:
+// a label the App Spec authors that label;
+// an update row's label it does not author the row's own label, from its fresh base read (an update keeps it);
+// a created row's label it does not author what the SDK fills it with at push — the same defaults, in the same order:
+// root (CustomApiAdapter.createDefault, `??`) name = uniqueName, displayName = uniqueName, description = displayName
+// child (CustomApiAdapter.normalize, `=== undefined`) name = '<api uniqueName>.<child uniqueName>', displayName = uniqueName,
+// description = displayName
+// The SDK leaves a label that is already set untouched, so pinning changes nothing it sends; the parity test in
+// tests/configuration-create-bindings.test.js holds this to the bundled SDK's own push of an unpinned artifact.
+function pinApiLabels(artifact, rootMode, slotModes, bases) {
+ const pin = (own, fallback, isSet) => {
+ const out = {};
+ for (const f of LABELS) out[f] = isSet(own[f]) ? own[f] : fallback(f, out);
+ Object.assign(own, out);
+ };
+ const rootId = normalizeGuid(artifact.id);
+ if (rootMode === 'update') {
+ const base = baseOf(bases, 'customApi', rootId, null);
+ pin(artifact, (f) => base.decoded.fields[f], (v) => v != null);
+ } else {
+ pin(artifact, (f, out) => (f === 'description' ? out.displayName : artifact.uniqueName), (v) => v != null);
+ }
+ for (const [list, prefix, childKind] of [[artifact.requestParameters, 'request:', 'customApiRequestParameter'], [artifact.responseProperties, 'response:', 'customApiResponseProperty']]) {
+ for (const child of list) {
+ if (slotModes.get(`${prefix}${lower(child.uniqueName)}`) === 'update') {
+ const base = baseOf(bases, childKind, normalizeGuid(child.id), rootId);
+ pin(child, (f) => base.decoded.fields[f], (v) => v !== undefined);
+ } else {
+ pin(child, (f, out) => (f === 'name' ? `${artifact.uniqueName}.${child.uniqueName}` : f === 'displayName' ? child.uniqueName : out.displayName), (v) => v !== undefined);
+ }
+ }
+ }
+}
+
+/**
+ * The protected create plan of ONE declared configuration artifact, at the ids the create port derives for it:
+ * planOf(spec, { kind, key, bindings?, solution?, intentFor?, boundIdOf?, componentTypes?, boundSlots?, keptChildren?, bases?, baseGeneration? })
+ * `kind` is a root kind and `key` its declared key (schema name, logical name, unique name, rule key). `bindings` are
+ * the deployment bindings (readDeploymentBindings): a bound value adds the value row, a bound connection makes the
+ * reference's connection a private input. `solution` is the run's solution (else the spec's, else Default); in a
+ * restricted solution (Default, Active) no membership is planned. `componentTypes` is readComponentTypes' `types`,
+ * needed whenever membership is. `boundIdOf(kind, portKey)` is a recorded binding's id (the root is then an update);
+ * `boundSlots` names children that already exist under it (updates, not creates). `keptChildren` ({ value: <id> }, a
+ * bound variable only) is a bound value the deployment settings do not name this run: held at its id, never sent. `bases` (a Map or an object, by row
+ * id) holds the fresh readConfigurationRow answer of every row the plan updates with a PATCH: its row version is the only
+ * If-Match the classifier admits for that row, and a Custom API row's labels the App Spec leaves out are kept from it.
+ * `baseGeneration` is the committed group's generation (the binding store's readGroup) an update is planned from: the
+ * store prepares the attempt only while the group is still at it.
+ * Answers a frozen planned object { kind, key, solution, plan, rows } — `plan` is buildRowPlan's input (with the root's
+ * `baseObservation` when it is an update read fresh); `rows` are its rows with what each must read back as
+ * (`expected`), for a child its slot, and for a PATCHed row its held row version (`ifMatch`). No private input is in
+ * either.
+ */
+function planOf(spec, { kind, key, bindings, solution, intentFor = defaultIntentFor, boundIdOf, componentTypes, boundSlots = [], keptChildren, bases, baseGeneration } = {}) {
+ if (!ROOT_KINDS.has(kind)) throw new TypeError(`planOf: ${kind} is not a configuration root kind`);
+ const entry = A.configurationIntentOf(spec, kind, key);
+ const sol = nonEmpty(solution) ? solution : spec && isPlain(spec.solution) && nonEmpty(spec.solution.uniqueName) ? spec.solution.uniqueName : 'Default';
+ const binds = bindings || { environmentVariables: new Map(), connectionReferences: new Map() };
+ const catalog = createIntentCatalog(A.configurationCreateIntents(spec, { intentFor, bindings: binds, boundIdOf, solution: sol }));
+ const portKey = A.portKeyOf(kind, entry[PLAN_KEY_FIELD[kind]]);
+ const got = catalog.get(kind, portKey);
+ if (!got) throw new TypeError(`planOf: no create identity for ${kind} "${portKey}"`);
+ let parentDefinitionId = null;
+ if (kind === 'environmentVariable' && entry.type === 'dataSource' && nonEmpty(entry.parentSchemaName)) {
+ const parent = catalog.get('environmentVariable', lower(entry.parentSchemaName));
+ if (!parent) throw new TypeError(`planOf: the parent definition "${entry.parentSchemaName}" of "${portKey}" is not declared`);
+ parentDefinitionId = parent.id;
+ }
+ const artifact = A.buildArtifact({ kind, key: portKey, detail: { entry } }, got.id, got.childIds, { bindings: binds }, parentDefinitionId);
+ const secrets = new Map();
+ const rootId = normalizeGuid(got.id);
+ const rootMode = got.intent.boundId !== undefined ? 'update' : 'create';
+ const bound = new Set(boundSlots);
+ if (kind === 'customApi') pinApiLabels(artifact, rootMode, new Map(Object.keys(got.childIds).map((s) => [s, bound.has(s) ? 'update' : 'create'])), bases);
+ const rootExpected = expectedOf(kind, artifact);
+ const root = {
+ kind, key: portKey, id: rootId, parentId: null, slot: null, mode: rootMode, sensitiveInput: false,
+ expected: rootMode === 'update' ? boundExpectation(kind, rootExpected, baseOf(bases, kind, rootId, null), entry, binds) : rootExpected,
+ };
+ if (kind === 'connectionReference' && artifact.connectionId != null && artifact.connectionId !== '') {
+ root.sensitiveInput = true;
+ secrets.set(rowKey(kind, portKey), artifact.connectionId);
+ }
+ const rows = [root];
+ for (const [slot, rawId] of Object.entries(got.childIds)) {
+ const childKind = childKindOf(kind, slot);
+ const id = normalizeGuid(rawId);
+ const children = kind === 'customApi' ? [...artifact.requestParameters, ...artifact.responseProperties] : kind === 'duplicateRule' ? artifact.conditions : [];
+ const child = children.find((c) => normalizeGuid(c.id) === id) || null;
+ if (childKind !== 'environmentVariableValue' && !child) throw new TypeError(`planOf: the ${slot} child of ${kind} "${portKey}" is not in its artifact`);
+ const mode = bound.has(slot) ? 'update' : 'create';
+ const created = expectedOf(childKind, artifact, child);
+ const row = {
+ kind: childKind, key: JSON.stringify([portKey, slot]), id, parentId: rootId, slot, mode,
+ expected: mode === 'update' ? boundExpectation(childKind, created, baseOf(bases, childKind, id, rootId), declaredChild(entry, slot), binds) : created,
+ sensitiveInput: childKind === 'environmentVariableValue',
+ };
+ // A condition's namesake is any condition of the rule its declaration describes (configuration-artifacts.js describes).
+ if (childKind === 'duplicateRuleCondition') row.declared = structuredClone((entry.conditions || []).find((c) => c.key === slot));
+ if (childKind === 'environmentVariableValue') secrets.set(rowKey(childKind, row.key), artifact.currentValue.value);
+ rows.push(row);
+ }
+ // A bound variable's value the declaration leaves alone this run (its deployment settings name no value): the bound
+ // row is still the variable's own child, so the plan holds it — present, under its definition, at its bound id — and
+ // an edit of the definition is not judged a conflict over it. Nothing can be sent for it: it holds no row version (a
+ // PATCH needs one: classifyPatch) and no private input (a value carried for it is refused: sendRow).
+ for (const [slot, rawId] of Object.entries(keptChildren || {})) {
+ if (kind !== 'environmentVariable' || slot !== 'value' || has(got.childIds, slot) || rootMode !== 'update') throw new TypeError(`planOf: ${kind} "${portKey}" cannot keep a bound ${slot} child`);
+ const id = normalizeGuid(rawId);
+ if (!id) throw new TypeError(`planOf: the kept ${slot} child of ${kind} "${portKey}" has no id`);
+ rows.push({ kind: 'environmentVariableValue', key: JSON.stringify([portKey, slot]), id, parentId: rootId, slot, mode: 'update', kept: true, expected: {}, sensitiveInput: false });
+ }
+ for (const r of rows) {
+ // An updated row keeps what its base read held in the columns this build never writes (PRESERVED): the exact value, so
+ // a row whose implementation was replaced or removed meanwhile is not the row this edit planned.
+ r.preserved = r.mode === 'update' && !r.kept ? { ...baseOf(bases, r.kind, r.id, r.parentId).decoded.preserved } : {};
+ r.expectedSha256 = projectionOf(r.kind, r.expected, r.expected, [], [], r.preserved);
+ if (r.mode === 'update' && !r.kept && PATCHABLE.has(r.kind)) r.ifMatch = baseOf(bases, r.kind, r.id, r.parentId).rowVersion;
+ }
+ // An update of a bound root records the versions it was prepared from (the binding store's baseObservation); they stay
+ // out of the declaration, which a later fresh read must not change.
+ const versions = rows.filter((r) => r.ifMatch !== undefined).map((r) => ({ kind: r.kind, id: r.id, rowVersion: r.ifMatch }));
+ const baseObservation = root.ifMatch !== undefined ? { rowVersion: root.ifMatch, savedSha256: sha({ rows: versions }) } : null;
+ const members = [];
+ if (!isRestrictedSolution(sol)) {
+ for (const r of rows) {
+ if (r.kind === 'environmentVariableValue') continue;
+ const table = MEMBER_TABLES[r.kind];
+ const componentType = typeof table === 'number' ? table : componentTypes && componentTypes[table];
+ if (!Number.isInteger(componentType)) throw new TypeError(`planOf: the component type of ${table} is not known; read it first (readComponentTypes)`);
+ members.push({ kind: r.kind, id: r.id, componentType });
+ }
+ }
+ const ruleState = kind !== 'duplicateRule' ? null
+ // A bound rule whose App Spec omits `status` keeps the state the row shows (as the existing planner does: a build
+ // never republishes a rule somebody unpublished); a create, or an authored status, is the declared state.
+ : rootMode === 'update' && entry.status === undefined ? boundRuleState(baseOf(bases, kind, rootId, null)) : artifact.status;
+ if (ruleState !== null && ruleState !== 'published' && ruleState !== 'unpublished') throw new TypeError(`planOf: rule status ${ruleState} is not one this driver plans`);
+ // A protected rule is published once, by the create set that makes it: only a plan whose rule row is a create holds the
+ // publish effect. A bound rule's plan keeps its state as a completion check (verified, never published again), so a
+ // rule found unpublished there is held, not republished.
+ const publishes = ruleState === 'published' && root.mode === 'create';
+ const planRows = rows.map(({ kind: k, key: rk, id, parentId, mode, expectedSha256, sensitiveInput }) => ({ kind: k, key: rk, id, parentId, mode, expectedSha256, sensitiveInput }));
+ const plan = {
+ family: kind, key: portKey,
+ declarationSha256: declarationSha256Of(spec, { kind, key, solution: sol, rows: planRows, ruleState }),
+ rows: planRows, members, ruleState,
+ effects: [...members.map((m) => ({ kind: 'membership', id: m.id })), ...(publishes ? [{ kind: 'rule-state', id: rootId }] : [])],
+ ...(baseObservation ? { baseObservation } : {}),
+ ...(rootMode === 'update' && baseGeneration !== undefined && baseGeneration !== null ? { baseGeneration } : {}),
+ };
+ const planned = deepFreeze({ kind, key: portKey, solution: sol, plan, rows });
+ PRIVATE_INPUTS.set(planned, { artifact, secrets });
+ return planned;
+}
+
+/**
+ * The declaration digest of a plan of `kind` `key` (planOf's plan.declarationSha256): today's declaration of the item,
+ * the solution, the plan rows ({ kind, key, id, parentId, mode, expectedSha256, sensitiveInput }; any other field is
+ * ignored) and the rule state. Given a pending attempt's OWN persisted rows and rule state, it is the digest that attempt
+ * was prepared with exactly when today's declaration is the one it was prepared for — so recovery judges the attempt by
+ * its original expectation, never by rows re-derived from today's reads.
+ */
+function declarationSha256Of(spec, { kind, key, solution, rows, ruleState = null }) {
+ const entry = A.configurationIntentOf(spec, kind, key);
+ const portKey = A.portKeyOf(kind, entry[PLAN_KEY_FIELD[kind]]);
+ const planRows = rows.map(({ kind: k, key: rk, id, parentId, mode, expectedSha256, sensitiveInput }) => ({ kind: k, key: rk, id, parentId, mode, expectedSha256, sensitiveInput: sensitiveInput === true }));
+ return sha({ kind, key: portKey, declaration: A.portableIntent(kind, entry), solution, rows: planRows, ruleState: ruleState === undefined ? null : ruleState });
+}
+
+function deepFreeze(o) {
+ if (o && typeof o === 'object' && !Object.isFrozen(o)) {
+ Object.freeze(o);
+ for (const v of Object.values(o)) deepFreeze(v);
+ }
+ return o;
+}
+
+function privateOf(planned) {
+ const p = PRIVATE_INPUTS.get(planned);
+ if (!p) throw new TypeError('the planned object was not made by planOf');
+ return p;
+}
+
+/** The SDK artifact of a planned object (sdk.createArtifact input): a fresh copy, private inputs included. */
+function artifactFor(planned) {
+ return structuredClone(privateOf(planned).artifact);
+}
+
+/** The run's `acceptResult` for the SDK's pushArtifact of `planned` (managed-create-context.js acceptSaved). */
+function acceptResultFor(planned) {
+ return acceptSaved({ type: planned.kind, id: planned.plan.rows[0].id });
+}
+
+// ---------------------------------------------------------------------------------------------
+// Reads. None throws: a failed, refused or malformed read is `unknown`, never absence and never a difference.
+
+function errorCode(body) {
+ let b = body;
+ if (typeof b === 'string') { try { b = JSON.parse(b); } catch { return null; } }
+ const e = isPlain(b) ? b.error || b.Error : null;
+ return isPlain(e) && typeof e.code === 'string' ? e.code.toLowerCase() : null;
+}
+
+// One read through the SDK's Dataverse reader: `get(path)` answers { status, body } (a 404 included) and may throw.
+async function answer(run) {
+ try {
+ const res = await run();
+ const status = res && Number.isInteger(res.status) ? res.status : null;
+ if (status !== null && status >= 200 && status < 300 && isPlain(res.body)) return { ok: true, status, body: res.body };
+ return { ok: false, status, code: errorCode(res && res.body) };
+ } catch (e) {
+ const status = e && Number.isInteger(e.statusCode) ? e.statusCode : e && Number.isInteger(e.status) ? e.status : null;
+ return { ok: false, status, code: errorCode(e && e.body) };
+ }
+}
+const canRead = (dv) => !!dv && typeof dv.get === 'function';
+
+// Dataverse's "does not exist" for a read by id: HTTP 404 with { "error": { "code": "0x80040217", ... } }. A 404
+// without it (a missing set, a proxy's page) proves nothing about the row.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/web-service-error-codes
+const NOT_FOUND = '0x80040217';
+
+/**
+ * One exact-id read of `kind` at `id`, every mapped column selected:
+ * GET /customapis(<id>)?$select=customapiid,uniquename,name,displayname,...,_plugintypeid_value
+ * { "@odata.etag": "W/\"1\"", "customapiid": "<id>", "uniquename": "contoso_Calc", ..., "_plugintypeid_value": null }
+ * Answers { state: 'present', kind, id, parentId, rowVersion, decoded } | { state: 'absent' } | { state: 'unknown', reason }.
+ * Present only when the answer names this id and carries every selected column (Dataverse answers `null` for an empty
+ * one) but the private one, whose absence is a masked value, not an unreadable row. `rowVersion` is the answer's
+ * `@odata.etag` when it is a row version (W/"<n>"), else null — a plan cannot update the row from such a read (planOf).
+ */
+async function readConfigurationRow(dataverse, kind, id) {
+ const k = KINDS[kind];
+ const want = normalizeGuid(id);
+ if (!k || !want) throw new TypeError(`readConfigurationRow: ${kind} ${id} is not a configuration row`);
+ if (!canRead(dataverse)) return { state: 'unknown', reason: 'no reader is available' };
+ const res = await answer(() => dataverse.get(`/${k.set}(${want})?$select=${[k.pk, ...Object.keys(k.columns)].join(',')}`));
+ if (!res.ok) {
+ if (res.status === 404 && res.code === NOT_FOUND) return { state: 'absent' };
+ return { state: 'unknown', reason: `the read failed (HTTP ${res.status})` };
+ }
+ if (normalizeGuid(res.body[k.pk]) !== want) return { state: 'unknown', reason: 'the read answered another row' };
+ if (Object.entries(k.columns).some(([col, spec]) => spec !== PRIVATE && !has(res.body, col))) return { state: 'unknown', reason: 'the read left out a selected column' };
+ const decoded = decode(kind, res.body, 'read');
+ if (!decoded) return { state: 'unknown', reason: 'a column holds a value this build cannot read' };
+ const etag = res.body['@odata.etag'];
+ const rowVersion = typeof etag === 'string' && ROW_VERSION.test(etag) ? etag : null;
+ return { state: 'present', kind, id: want, parentId: decoded.parentId === undefined ? null : decoded.parentId, rowVersion, decoded };
+}
+
+/**
+ * Every page of one collection read. Dataverse pages with an absolute `@odata.nextLink`:
+ * { "value": [ ... ], "@odata.nextLink": "https://contoso.crm.dynamics.com/api/data/v9.2/customapis?$select=...&$skiptoken=..." }
+ * and may flag `"@Microsoft.Dynamics.CRM.morerecords": true`. A later page is read through the SDK's same-origin
+ * absolute reader (getAbsolute); a failed page, a page without a `value` list, a link that is not an absolute URL or
+ * repeats one already followed, and a "more records" flag without a link leave the read INCOMPLETE — and an
+ * incomplete namesake query proves no absence, even when every page it did read was empty.
+ * See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query/page-results
+ */
+async function readAllPages(dataverse, path) {
+ if (!canRead(dataverse)) return { complete: false, reason: 'no reader is available' };
+ const rows = [];
+ const links = new Set();
+ let page = await answer(() => dataverse.get(path));
+ for (;;) {
+ if (!page.ok) return { complete: false, reason: `a page could not be read (HTTP ${page.status})` };
+ if (!Array.isArray(page.body.value)) return { complete: false, reason: 'a page is not a list' };
+ rows.push(...page.body.value);
+ const next = page.body['@odata.nextLink'];
+ if (next === undefined || next === null) {
+ if (page.body['@Microsoft.Dynamics.CRM.morerecords'] === true) return { complete: false, reason: 'more records were flagged without a link to them' };
+ return { complete: true, rows };
+ }
+ let absolute = false;
+ try { absolute = typeof next === 'string' && /^https:$/i.test(new URL(next).protocol); } catch { absolute = false; }
+ if (!absolute || links.has(next) || typeof dataverse.getAbsolute !== 'function') return { complete: false, reason: 'the read continues on a page this build cannot follow' };
+ links.add(next);
+ page = await answer(() => dataverse.getAbsolute(next));
+ }
+}
+
+/** The ObjectTypeCode of each member table: { complete: true, types: { customapi: 10133, ... } } or { complete: false, reason }. */
+async function readComponentTypes(dataverse) {
+ const types = {};
+ for (const table of new Set(Object.values(MEMBER_TABLES).filter((t) => typeof t === 'string'))) {
+ // GET /EntityDefinitions(LogicalName='customapi')?$select=ObjectTypeCode -> { "ObjectTypeCode": 10133, "MetadataId": "..." }
+ const res = canRead(dataverse) ? await answer(() => dataverse.get(`/EntityDefinitions(LogicalName='${table}')?$select=ObjectTypeCode`)) : { ok: false };
+ if (!res.ok || !Number.isInteger(res.body.ObjectTypeCode)) return { complete: false, reason: `the component type of ${table} could not be read` };
+ types[table] = res.body.ObjectTypeCode;
+ }
+ return { complete: true, types };
+}
+
+const lit = (v) => `'${encodeURIComponent(odataLit(v))}'`;
+
+// The namesake query of one planned create row, and how a returned row is judged: 'hit' (a namesake), 'other' (a row
+// the query may return that is no namesake: another parameter of the same API, another condition of the same rule)
+// or BAD (a row the predicate does not hold for: the answer is not the query's, so nothing it says is trusted).
+// environment variable schemaname eq '<schema name>' (any definition, any solution)
+// connection reference connectionreferencelogicalname eq '<logical name>'
+// Custom API uniquename eq '<unique name>'
+// duplicate rule name eq '<name>' (ANY table: a rule's name is the maker's handle)
+// value _environmentvariabledefinitionid_value eq <definition id> (one value per definition)
+// request parameter /
+// response property _customapiid_value eq <api id>, then the unique name, case-insensitive, in that direction only
+// condition _regardingobjectid_value eq <rule id>, then every condition the declaration describes
+// String equality in a Dataverse $filter is case-insensitive, so a returned namesake is compared the same way.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query/filter-rows
+function conflictQueryOf(row) {
+ const k = KINDS[row.kind];
+ if (ROOT_KINDS.has(row.kind)) {
+ const name = row.expected[k.nameField];
+ return {
+ path: `/${k.set}?$select=${k.pk},${k.name}&$filter=${k.name} eq ${lit(name)}`,
+ judge: (r) => (typeof r[k.name] === 'string' && lower(r[k.name]) === lower(name) ? 'hit' : BAD),
+ };
+ }
+ const parentOk = (r) => normalizeGuid(r[k.parentColumn]) === row.parentId;
+ const base = `/${k.set}?$filter=${k.parentColumn} eq ${row.parentId}&$select=`;
+ if (row.kind === 'environmentVariableValue') {
+ return { path: `${base}${k.pk},${k.parentColumn}`, judge: (r) => (parentOk(r) ? 'hit' : BAD) };
+ }
+ if (row.kind === 'duplicateRuleCondition') {
+ return {
+ path: `${base}${[k.pk, ...Object.keys(k.columns)].join(',')}`,
+ judge: (r) => {
+ const d = decode(row.kind, r, 'read');
+ if (!d || !parentOk(r)) return BAD;
+ return A.describes(row.declared, d.fields) ? 'hit' : 'other';
+ },
+ };
+ }
+ return {
+ path: `${base}${k.pk},uniquename,${k.parentColumn}`,
+ judge: (r) => {
+ if (!parentOk(r) || typeof r.uniquename !== 'string') return BAD;
+ return lower(r.uniquename) === lower(row.expected.uniqueName) ? 'hit' : 'other';
+ },
+ };
+}
+
+async function readRowConflicts(dataverse, row) {
+ const k = KINDS[row.kind];
+ const q = conflictQueryOf(row);
+ const read = await readAllPages(dataverse, q.path);
+ if (!read.complete) return { state: 'unknown', reason: read.reason };
+ const ids = [];
+ for (const r of read.rows) {
+ const id = isPlain(r) && typeof r[k.pk] === 'string' ? normalizeGuid(r[k.pk]) : '';
+ if (!id) return { state: 'unknown', reason: 'the namesake query answered a row without an id' };
+ const verdict = q.judge(r);
+ if (verdict === BAD) return { state: 'unknown', reason: 'the namesake query answered a row its filter does not hold for' };
+ if (verdict !== 'hit') continue;
+ // The derived id itself answering the namesake query right after its exact read found nothing: the two reads
+ // disagree, and neither is taken.
+ if (id === row.id) return { state: 'unknown', reason: 'the namesake query answered the planned id itself' };
+ if (!ids.includes(id)) ids.push(id);
+ }
+ return ids.length ? { state: 'conflict', ids } : { state: 'clear' };
+}
+
+/**
+ * The namesake queries a protected create must run, complete, before it sends anything — one per planned CREATE row,
+ * every page followed (readAllPages). Run after the exact reads found those rows absent. Answers
+ * { state: 'clear' | 'conflict' | 'unknown', code: null | create-identity-conflict | create-identity-unverified, rows }
+ * with `rows` [{ kind, key, state, ids?, reason? }]. Any unknown query answers unknown (nothing is created on a read
+ * that may have missed a namesake), before any conflict; a namesake at another id is a conflict, whatever approval the
+ * maker holds: an approval adopts the row AT the derived id, never a row elsewhere.
+ */
+async function readConfigurationConflicts(dataverse, planned) {
+ privateOf(planned);
+ const rows = [];
+ for (const row of planned.rows) {
+ if (row.mode !== 'create') continue;
+ rows.push({ kind: row.kind, key: row.key, ...(await readRowConflicts(dataverse, row)) });
+ }
+ if (rows.some((r) => r.state === 'unknown')) return { state: 'unknown', code: CODES.unverified, rows };
+ if (rows.some((r) => r.state === 'conflict')) return { state: 'conflict', code: CODES.conflict, rows };
+ return { state: 'clear', code: null, rows };
+}
+
+/**
+ * The membership of every planned member in the plan's solution, from a complete read of the solution's components of
+ * the planned types (and the classic duplicate-rule types 44 and 45, which the platform may still list a rule or a
+ * condition under):
+ * GET /solutions?$select=solutionid,uniquename&$filter=uniquename eq 'ContosoSol'
+ * GET /solutioncomponents?$select=objectid,componenttype,_solutionid_value&$filter=_solutionid_value eq <id> and (componenttype eq 380 or ...)
+ * { "value": [ { "objectid": "<guid>", "componenttype": 10133, "_solutionid_value": "<id>" } ], "@odata.nextLink": ... }
+ * Ids are matched here, not in the filter, so one read serves every member. Any incomplete or malformed answer makes
+ * EVERY member unknown: a missing page could hold any of them.
+ * See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/solutioncomponent
+ */
+async function readMembers(dataverse, planned) {
+ const want = planned.plan.members;
+ if (!want.length) return [];
+ const unknown = () => want.map((m) => ({ id: m.id, state: 'unknown' }));
+ const sol = await readAllPages(dataverse, `/solutions?$select=solutionid,uniquename&$filter=uniquename eq ${lit(planned.solution)}`);
+ if (!sol.complete || sol.rows.length !== 1) return unknown();
+ const s = sol.rows[0];
+ const sid = isPlain(s) && typeof s.solutionid === 'string' ? normalizeGuid(s.solutionid) : '';
+ if (!sid || typeof s.uniquename !== 'string' || lower(s.uniquename) !== lower(planned.solution)) return unknown();
+ const classic = (m) => A.CLASSIC_MEMBERSHIP_TYPES[m.kind];
+ const types = [...new Set(want.flatMap((m) => [m.componentType, ...(classic(m) ? [classic(m)] : [])]))].sort((a, b) => a - b);
+ const filter = `_solutionid_value eq ${sid} and (${types.map((t) => `componenttype eq ${t}`).join(' or ')})`;
+ const comps = await readAllPages(dataverse, `/solutioncomponents?$select=objectid,componenttype,_solutionid_value&$filter=${filter}`);
+ if (!comps.complete) return unknown();
+ const present = new Set();
+ for (const c of comps.rows) {
+ const id = isPlain(c) && typeof c.objectid === 'string' ? normalizeGuid(c.objectid) : '';
+ if (!id || !types.includes(c.componenttype) || normalizeGuid(c._solutionid_value) !== sid) return unknown();
+ present.add(`${id}|${c.componenttype}`);
+ }
+ return want.map((m) => ({
+ id: m.id,
+ state: present.has(`${m.id}|${m.componentType}`) || (classic(m) && present.has(`${m.id}|${classic(m)}`)) ? 'present' : 'absent',
+ }));
+}
+
+// A private input read back, compared in memory with the planned one:
+// match the row holds exactly the planned input;
+// masked the column was not returned, or came back as a run of asterisks (a secret the platform will not show);
+// mismatch the row holds another input;
+// unknown there is no planned input to compare with.
+function privateStateOf(read, want) {
+ if (want === undefined) return 'unknown';
+ if (!read.present) return 'masked';
+ if (read.value === want) return 'match';
+ if (typeof read.value === 'string' && /^\*+$/.test(read.value)) return 'masked';
+ return 'mismatch';
+}
+
+/**
+ * The complete child graph under a present root, against the plan: every child collection of the root's kind, filtered by
+ * the parent lookup and read to its last page (readAllPages):
+ * GET /customapirequestparameters?$select=customapirequestparameterid,_customapiid_value&$filter=_customapiid_value eq <root id>
+ * { "value": [ { "customapirequestparameterid": "<guid>", "_customapiid_value": "<root id>" } ], "@odata.nextLink": ... }
+ * (the same for response properties, a rule's conditions by _regardingobjectid_value and a definition's values by
+ * _environmentvariabledefinitionid_value). Answers { state: 'complete', unexpected: ['<kind>:<id>', ...] } or
+ * { state: 'unknown' } when a collection is not read completely, answers a row without an id or under another parent,
+ * names a row twice, or disagrees with the exact reads about a planned child (listed but read absent, or the reverse).
+ * The exact reads alone prove only the planned children: a row someone else added under the root would never be asked
+ * about, and the rule, API or definition it changes would still be judged the one the plan made.
+ */
+async function readChildGraph(dataverse, planned, exact) {
+ const rootId = planned.plan.rows[0].id;
+ const unexpected = [];
+ for (const [childKind, k] of Object.entries(KINDS)) {
+ if (!k.parentSet || k.parentSet !== KINDS[planned.kind].set) continue;
+ const read = await readAllPages(dataverse, `/${k.set}?$select=${k.pk},${k.parentColumn}&$filter=${k.parentColumn} eq ${rootId}`);
+ if (!read.complete) return { state: 'unknown' };
+ const listed = new Set();
+ for (const r of read.rows) {
+ const id = isPlain(r) && typeof r[k.pk] === 'string' ? normalizeGuid(r[k.pk]) : '';
+ if (!id || listed.has(id) || normalizeGuid(r[k.parentColumn]) !== rootId) return { state: 'unknown' };
+ listed.add(id);
+ }
+ const plannedIds = new Set();
+ for (const row of planned.rows) {
+ if (row.kind !== childKind) continue;
+ plannedIds.add(row.id);
+ const seen = exact.get(row.id);
+ if (seen === 'unknown') continue;
+ if ((seen === 'present') !== listed.has(row.id)) return { state: 'unknown' };
+ }
+ for (const id of listed) if (!plannedIds.has(id)) unexpected.push(`${childKind}:${id}`);
+ }
+ return { state: 'complete', unexpected: unexpected.sort() };
+}
+
+/**
+ * The fresh observation the lifecycle judges (managed-create-context.js classifyRecovery / settle):
+ * { rows: [{ kind, key, id, state, parentId?, projectionSha256?, privateState? }], members: [{ id, state }], ruleState }
+ * One exact-id read per planned row (readConfigurationRow), the root's complete child graph (readChildGraph), the
+ * solution's members (readMembers) and the rule's state from its own read. The graph is judged on the root row, the one
+ * row the lifecycle compares for the whole artifact: a child the plan does not hold makes the root's projection differ
+ * (a conflict: it is neither deleted nor adopted), and a graph that cannot be read completely makes the root unknown —
+ * so no completion is proven from a partial graph. An absent rule is reported unpublished — there is no rule to be
+ * published — so its absence is judged as the missing row it is; an unreadable or publishing rule leaves the state unknown.
+ */
+async function observe(dataverse, planned) {
+ const { secrets } = privateOf(planned);
+ const rows = [];
+ const exact = new Map();
+ let rootRead = null;
+ let ruleState = null;
+ for (const r of planned.rows) {
+ const read = await readConfigurationRow(dataverse, r.kind, r.id);
+ exact.set(r.id, read.state);
+ if (r.parentId === null) rootRead = read;
+ if (r.kind === 'duplicateRule') ruleState = read.state === 'absent' ? 'unpublished' : read.state === 'present' ? ruleStateOf(read.decoded.state.statecode, read.decoded.state.statuscode) : undefined;
+ if (read.state !== 'present') {
+ rows.push({ kind: r.kind, key: r.key, id: r.id, state: read.state });
+ continue;
+ }
+ const out = {
+ kind: r.kind, key: r.key, id: read.id, state: 'present', parentId: read.parentId,
+ projectionSha256: projectionOf(r.kind, r.expected, semanticOf(r.kind, read.decoded), read.decoded.unmodelled, [], read.decoded.preserved),
+ };
+ if (r.sensitiveInput) out.privateState = privateStateOf(read.decoded.private, secrets.get(rowKey(r.kind, r.key)));
+ rows.push(out);
+ }
+ if (rootRead && rootRead.state === 'present') {
+ const root = planned.rows[0];
+ const graph = await readChildGraph(dataverse, planned, exact);
+ if (graph.state !== 'complete') rows[0] = { kind: root.kind, key: root.key, id: root.id, state: 'unknown' };
+ else if (graph.unexpected.length) {
+ rows[0].projectionSha256 = projectionOf(root.kind, root.expected, semanticOf(root.kind, rootRead.decoded), rootRead.decoded.unmodelled, graph.unexpected, rootRead.decoded.preserved);
+ }
+ }
+ return { rows, members: await readMembers(dataverse, planned), ruleState };
+}
+
+/**
+ * What a bound plan would change, read fresh and sent nowhere — the build's read-only preflight decides from it whether
+ * the change is one the protected path can make:
+ * { state: 'complete', rootChanged, creates: [kind], labelEdits: [kind], fixedEdits: [kind], removals: ['<kind>:<id>'],
+ * missing: [{ kind, key, id }], ruleStateChanged } or { state: 'unknown' }
+ * One exact-id read per planned row and the root's complete child graph (readChildGraph), as observe reads them. A bound
+ * row that differs from its expectation is an edit: of the root, of a child's labels only (`labelEdits`: name, display
+ * name, description — what the SDK PATCHes in place), or of anything else (`fixedEdits`). A planned create the read finds
+ * present, an unreadable row or a graph that cannot be read completely is unknown: nothing is judged from a partial read.
+ * A child under the root the plan does not hold is a removal (`removals`); a bound row read absent is `missing`.
+ */
+async function editShapeOf(dataverse, planned) {
+ const out = { state: 'complete', rootChanged: false, creates: [], labelEdits: [], fixedEdits: [], removals: [], missing: [], ruleStateChanged: false };
+ const exact = new Map();
+ let rootPresent = false;
+ for (const r of planned.rows) {
+ const read = await readConfigurationRow(dataverse, r.kind, r.id);
+ exact.set(r.id, read.state);
+ if (read.state === 'unknown') return { state: 'unknown' };
+ if (r.mode === 'create') {
+ if (read.state !== 'absent') return { state: 'unknown' };
+ out.creates.push(r.kind);
+ continue;
+ }
+ if (read.state === 'absent') {
+ out.missing.push({ kind: r.kind, key: r.key, id: r.id });
+ continue;
+ }
+ if (r.parentId === null) rootPresent = true;
+ if (r.kind === 'duplicateRule') {
+ const now = ruleStateOf(read.decoded.state.statecode, read.decoded.state.statuscode);
+ if (now !== planned.plan.ruleState) out.ruleStateChanged = true;
+ }
+ const semantic = semanticOf(r.kind, read.decoded);
+ if (projectionOf(r.kind, r.expected, semantic, read.decoded.unmodelled, [], read.decoded.preserved) === r.expectedSha256) continue;
+ if (r.parentId === null) {
+ out.rootChanged = true;
+ continue;
+ }
+ // Which fields differ, compared as the plan holds them; a difference the field comparison cannot place (a column the
+ // projection normalizes, an unmodelled one) is not provably a label edit, so it is a fixed edit.
+ const differing = Object.keys(r.expected).filter((f) => canonicalJson(r.expected[f] === undefined ? null : r.expected[f]) !== canonicalJson(semantic[f] === undefined ? null : semantic[f]));
+ if (differing.length && differing.every((f) => LABELS.includes(f)) && API_KINDS.has(r.kind)) out.labelEdits.push(r.kind);
+ else out.fixedEdits.push(r.kind);
+ }
+ if (rootPresent) {
+ const graph = await readChildGraph(dataverse, planned, exact);
+ if (graph.state !== 'complete') return { state: 'unknown' };
+ out.removals = graph.unexpected;
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------------------------
+// The classifier: which planned row, or which completion effect, one mutation is. Anything else answers null (the
+// gate refuses it unsent). Every check is against the plan, never against what the request says about itself.
+
+const KIND_OF_SET = Object.freeze(Object.fromEntries(Object.entries(KINDS).map(([kind, k]) => [k.set, kind])));
+const API_KINDS = new Set(['customApi', 'customApiRequestParameter', 'customApiResponseProperty']);
+const PATCHABLE = new Set(['environmentVariable', 'environmentVariableValue', 'connectionReference', 'customApi', 'customApiRequestParameter', 'customApiResponseProperty']);
+// What the SDK's Custom API adapter PATCHes in place: a root's editable fields, and a child's labels only — a child's
+// type, optionality and table are fixed once created (configuration-artifacts.js refuses a change to them).
+const API_ROOT_EDITABLE = new Set(['name', 'displayname', 'description', 'isprivate', 'executeprivilegename']);
+const API_CHILD_EDITABLE = new Set(['name', 'displayname', 'description']);
+const API_CHILD_KINDS = new Set(['customApiRequestParameter', 'customApiResponseProperty']);
+// The deep-insert navigations of a root: the child kinds created inside its POST.
+const navsOf = (kind) => Object.entries(KINDS).filter(([, k]) => k.nav && k.parentSet === KINDS[kind].set).map(([childKind, k]) => [k.nav, childKind]);
+
+// A request body as the HTTP client hands it to the gate: the JSON text it sends (a string or a Buffer), or an object.
+function parseBody(body) {
+ if (body === undefined || body === null) return { empty: true };
+ if (isPlain(body)) return { empty: false, json: body };
+ const textOf = Buffer.isBuffer(body) ? body.toString('utf8') : typeof body === 'string' ? body : null;
+ if (textOf === null) return { empty: false, json: null };
+ if (!textOf.trim()) return { empty: true };
+ try {
+ const json = JSON.parse(textOf);
+ return { empty: false, json: isPlain(json) ? json : null };
+ } catch {
+ return { empty: false, json: null };
+ }
+}
+
+// The query options of a request, decoded. The SDK percent-encodes an $expand's inner options:
+// customapis?$select=customapiid&$expand=CustomAPIRequestParameters(%24select%3Dcustomapirequestparameterid)%2C...
+// A repeated option is two answers to one question: null.
+function queryOf(url) {
+ let params;
+ try { params = new URL(String(url), 'https://contoso.crm.dynamics.com').searchParams; } catch { return null; }
+ const out = {};
+ for (const [key, value] of params) {
+ if (has(out, key)) return null;
+ out[key] = value;
+ }
+ return out;
+}
+
+// The query a create of `kind` may carry: none, `$select=<its primary key>` (return=representation's id), and for a
+// Custom API root an $expand of exactly its child collections, each selecting only its own primary key — so the answer
+// names the ids the platform saved and nothing else.
+function createQueryOk(kind, query) {
+ const k = KINDS[kind];
+ for (const [key, value] of Object.entries(query)) {
+ if (key === '$select') { if (value !== k.pk) return false; continue; }
+ if (key === '$expand' && kind === 'customApi') {
+ const navs = new Map(navsOf(kind).map(([nav, childKind]) => [nav, KINDS[childKind].pk]));
+ const seen = new Set();
+ for (const item of value.split(',')) {
+ const m = /^([A-Za-z_]+)\(\$select=([a-z_]+)\)$/.exec(item);
+ if (!m || !navs.has(m[1]) || navs.get(m[1]) !== m[2] || seen.has(m[1])) return false;
+ seen.add(m[1]);
+ }
+ continue;
+ }
+ return false;
+ }
+ return true;
+}
+
+// A solution header may only name the plan's solution; a value row must carry none (it is never a member).
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/compose-http-requests-handle-errors#other-headers
+function solutionHeaderOk(planned, kind, headers) {
+ const named = headerValue(headers, 'mscrm.solutionuniquename');
+ if (named === null) return true;
+ return kind !== 'environmentVariableValue' && lower(named) === lower(planned.solution);
+}
+
+function privateMismatch(row) {
+ // The message names the row only: the input it was compared with is private, and so is what was about to be sent.
+ return Object.assign(new Error(`the ${row.kind} "${row.key}" was about to be sent with another private input than the one planned; it was not sent`), { code: PRIVATE_MISMATCH });
+}
+
+/**
+ * One planned row as a request carries it, or null. `raw` is the row's own object (a deep-insert child's array item);
+ * `how` is 'create' (a POST, nested or not) or 'patch'. The body must decode through the kind's closed map with no
+ * unmodelled column and none it preserves, sit under the planned parent (a nested child binds none — its parent is the root it is inside;
+ * any other child binds exactly its planned parent; a root binds none), and say exactly what the plan expects: every
+ * semantic field equal and nothing more (a Custom API's labels included: the plan pins them). A private input other than the planned one
+ * throws (PRIVATE_MISMATCH) rather than answer null, so the run reports it as the local failure it is. The sealed
+ * projection covers the semantic fields only: never a private input.
+ */
+function sendRow(planned, row, raw, how, nested) {
+ const d = decode(row.kind, raw, how);
+ if (!d || d.unmodelled.length) return null;
+ // Where the body puts the row: a nested child and a root bind no parent; a child created on its own binds exactly its
+ // planned parent; a PATCH may leave the parent unsaid, never name another one.
+ const parentOk = nested || row.parentId === null ? d.parentId === undefined
+ : how === 'create' ? d.parentId === row.parentId
+ : d.parentId === undefined || d.parentId === row.parentId;
+ if (!parentOk) return null;
+ const sem = semanticOf(row.kind, d, how);
+ for (const [f, v] of Object.entries(sem)) {
+ if (!has(row.expected, f) || !sameValue(v, row.expected[f])) return null;
+ }
+ if (how === 'create' && Object.keys(row.expected).some((f) => !has(sem, f))) return null;
+ if (d.private.present) {
+ const want = privateOf(planned).secrets.get(rowKey(row.kind, row.key));
+ if (!row.sensitiveInput) { if (d.private.value !== null && d.private.value !== '') return null; }
+ else if (d.private.value !== want) throw privateMismatch(row);
+ } else if (row.sensitiveInput && how === 'create') {
+ throw privateMismatch(row);
+ }
+ const projected = { ...sem, ...(row.parentId ? { parentId: row.parentId } : {}) };
+ return { kind: row.kind, key: row.key, id: row.id, parentId: row.parentId, ...sentProjection(projected) };
+}
+
+function indexOf(entries) {
+ if (!Array.isArray(entries) || entries.length === 0) throw new TypeError('createClassifier needs at least one { token, planned } entry');
+ const byId = new Map();
+ for (const { token, planned } of entries) {
+ privateOf(planned);
+ if (!nonEmpty(token)) throw new TypeError('createClassifier: an entry has no attempt token');
+ for (const row of planned.rows) {
+ // Two artifacts planning one id would make every request about it ambiguous.
+ if (byId.has(row.id)) throw new TypeError(`createClassifier: the id ${row.id} is planned twice`);
+ byId.set(row.id, { token, planned, row });
+ }
+ }
+ return byId;
+}
+
+function classifyCreate(byId, req, kind, body, constituent) {
+ const k = KINDS[kind];
+ const hit = typeof body[k.pk] === 'string' ? byId.get(normalizeGuid(body[k.pk]) || '') : undefined;
+ if (!hit || hit.row.kind !== kind || hit.row.mode !== 'create') return null;
+ const { token, planned, row } = hit;
+ // A condition exists only inside its rule's deep insert; a root is created only by its own POST, never in a $batch.
+ if (kind === 'duplicateRuleCondition' || (constituent && row.parentId === null)) return null;
+ const query = queryOf(req.url);
+ if (!query || !createQueryOk(kind, query) || !solutionHeaderOk(planned, kind, req.headers)) return null;
+ // A change-set child is the SDK's later child of a BOUND Custom API, in exactly its shape:
+ // POST /customapirequestparameters?$select=customapirequestparameterid { ..., "[email protected]": "/customapis(<bound id>)" }
+ if (constituent) {
+ const parent = planned.rows.find((r) => r.id === row.parentId);
+ if (!parent || parent.mode !== 'update' || Object.keys(query).length !== 1 || query.$select !== k.pk) return null;
+ }
+ const own = { ...body };
+ const nested = [];
+ for (const [nav, childKind] of row.parentId === null ? navsOf(kind) : []) {
+ if (!has(own, nav)) continue;
+ const list = own[nav];
+ delete own[nav];
+ if (!Array.isArray(list)) return null;
+ for (const item of list) {
+ const ck = KINDS[childKind];
+ const c = isPlain(item) && typeof item[ck.pk] === 'string' ? byId.get(normalizeGuid(item[ck.pk]) || '') : undefined;
+ if (!c || c.planned !== planned || c.row.kind !== childKind || c.row.mode !== 'create' || c.row.parentId !== row.id) return null;
+ if (nested.some((n) => n.row === c.row)) return null;
+ nested.push({ row: c.row, raw: item, nav });
+ }
+ }
+ // A root's deep insert carries every child the plan creates under it, and nothing else: a child left out would be
+ // sent later under a parent the answer has not proven, and a rule's condition cannot be sent any other way.
+ if (row.parentId === null) {
+ const want = planned.rows.filter((r) => r.parentId === row.id && r.mode === 'create' && navsOf(kind).some(([, ck]) => ck === r.kind));
+ if (want.length !== nested.length) return null;
+ }
+ const rows = [sendRow(planned, row, own, 'create', false)];
+ for (const n of nested) {
+ const sent = sendRow(planned, n.row, n.raw, 'create', true);
+ if (sent) sent.answer = { at: n.nav, key: KINDS[n.row.kind].pk, match: { [KINDS[n.row.kind].pk]: n.row.id } };
+ rows.push(sent);
+ }
+ if (rows.some((r) => !r)) return null;
+ return { type: 'rows', token, rows, expectTable: k.set, expectKey: k.pk };
+}
+
+// The If-Match of a PATCH, which must be exactly the row version the plan holds for the row (planOf `bases`):
+// If-Match: W/"3"
+// A missing header, the wildcard `*`, another or older version, a list of versions, or two spellings of the header
+// (If-Match and if-match, which could each be read as THE condition) is no condition the plan holds.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/perform-conditional-operations-using-web-api#apply-optimistic-concurrency
+function ifMatchOk(headers, held) {
+ const values = Object.entries(isPlain(headers) ? headers : {}).filter(([name]) => name.toLowerCase() === 'if-match').map(([, v]) => v);
+ return typeof held === 'string' && ROW_VERSION.test(held) && values.length === 1 && values[0] === held;
+}
+
+// The PATCH of one planned update row, as the SDK sends it:
+// PATCH /customapis(<id>)?$select=customapiid If-Match: W/"3" MSCRM.SolutionUniqueName: ContosoSol { "isprivate": true }
+// PATCH /customapirequestparameters(<id>)?$select=customapirequestparameterid If-Match: W/"9" { "description": "Arg" }
+// The query is exactly the selected primary key (return=representation's id). A Custom API child is PATCHed only for its
+// labels, and only on its own: in a change set (`constituent`) only the bound root's PATCH of its editable fields is a
+// shape a reviewed change-set parser may admit.
+function classifyPatch(byId, req, kind, rawId, body, constituent) {
+ const id = normalizeGuid(rawId);
+ const hit = id ? byId.get(id) : undefined;
+ if (!hit || hit.row.kind !== kind || hit.row.mode !== 'update' || !PATCHABLE.has(kind)) return null;
+ const keys = Object.keys(body);
+ if (constituent && (kind !== 'customApi' || !keys.length || !keys.every((c) => API_ROOT_EDITABLE.has(c)))) return null;
+ if (API_CHILD_KINDS.has(kind) && (!keys.length || !keys.every((c) => API_CHILD_EDITABLE.has(c)))) return null;
+ const k = KINDS[kind];
+ const query = queryOf(req.url);
+ if (!query || Object.keys(query).length !== 1 || query.$select !== k.pk) return null;
+ if (!ifMatchOk(req.headers, hit.row.ifMatch) || !solutionHeaderOk(hit.planned, kind, req.headers)) return null;
+ const sent = sendRow(hit.planned, hit.row, body, 'patch', false);
+ if (!sent) return null;
+ return { type: 'rows', token: hit.token, rows: [sent], expectTable: k.set, expectKey: k.pk };
+}
+
+// AddSolutionComponent of one planned member, in exactly the shape the SDK sends:
+// POST /AddSolutionComponent { "ComponentId": "<guid>", "ComponentType": 10133, "SolutionUniqueName": "ContosoSol", "AddRequiredComponents": false }
+// AddRequiredComponents must be false: true would pull every dependency into the solution, rows this plan never made.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/addsolutioncomponent
+function classifyMembership(byId, req, body) {
+ const keys = Object.keys(body).sort().join(',');
+ if (keys !== 'AddRequiredComponents,ComponentId,ComponentType,SolutionUniqueName' || body.AddRequiredComponents !== false) return null;
+ const id = typeof body.ComponentId === 'string' ? normalizeGuid(body.ComponentId) : '';
+ const hit = id ? byId.get(id) : undefined;
+ if (!hit || typeof body.SolutionUniqueName !== 'string' || lower(body.SolutionUniqueName) !== lower(hit.planned.solution)) return null;
+ if (!hit.planned.plan.members.some((m) => m.id === id && m.componentType === body.ComponentType)) return null;
+ const query = queryOf(req.url);
+ if (!query || Object.keys(query).length) return null;
+ return { type: 'effect', token: hit.token, kind: 'membership', id };
+}
+
+// The publish of a rule its own create set made, whose declared state is published (the plan's rule-state effect):
+// POST /duplicaterules(<guid>)/Microsoft.Dynamics.CRM.PublishDuplicateRule {}
+// A bound rule's plan holds no such effect (planOf): a rule is published once, when it is created, and only verified after.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/publishduplicaterule
+function classifyPublish(byId, req, rawId, parsed) {
+ const id = normalizeGuid(rawId);
+ const hit = id ? byId.get(id) : undefined;
+ if (!hit || hit.row.kind !== 'duplicateRule' || hit.row.mode !== 'create') return null;
+ if (!hit.planned.plan.effects.some((e) => e.kind === 'rule-state' && e.id === id)) return null;
+ if (!parsed.empty && !(isPlain(parsed.json) && Object.keys(parsed.json).length === 0)) return null;
+ const query = queryOf(req.url);
+ if (!query || Object.keys(query).length) return null;
+ return { type: 'effect', token: hit.token, kind: 'rule-state', id };
+}
+
+const ENTITY_BY_ID = /^([a-z]+)\(([^()]+)\)$/;
+const PUBLISH = /^duplicaterules\(([^()]+)\)\/Microsoft\.Dynamics\.CRM\.PublishDuplicateRule$/;
+
+function classifyWith(byId, req, constituent) {
+ const method = String((req && req.method) || '').toUpperCase();
+ let path;
+ try { path = apiPath(req && req.url); } catch { return null; }
+ if (!path) return null;
+ const parsed = parseBody(req.body);
+ if (method === 'POST') {
+ const publish = PUBLISH.exec(path);
+ if (publish) return constituent ? null : classifyPublish(byId, req, publish[1], parsed);
+ if (parsed.empty || !parsed.json) return null;
+ if (path === 'AddSolutionComponent') return constituent ? null : classifyMembership(byId, req, parsed.json);
+ const kind = has(KIND_OF_SET, path) ? KIND_OF_SET[path] : null;
+ return kind ? classifyCreate(byId, req, kind, parsed.json, constituent) : null;
+ }
+ if (method === 'PATCH') {
+ const m = ENTITY_BY_ID.exec(path);
+ const kind = m && has(KIND_OF_SET, m[1]) ? KIND_OF_SET[m[1]] : null;
+ if (!kind || parsed.empty || !parsed.json) return null;
+ return classifyPatch(byId, req, kind, m[2], parsed.json, constituent);
+ }
+ return null;
+}
+
+/**
+ * The gate's classifier (runWithManagedCreateSet `classify`) for the planned objects of one create set:
+ * createClassifier([{ token, planned }, ...]) -> ({ method, url, body, headers }) -> descriptor | null
+ * A descriptor names the attempt (`token`) and the planned rows a request carries, with their sealed non-private
+ * projection — or the membership / rule-state effect it is. Null for everything else: a row not planned, planned as
+ * an update but POSTed (or the reverse), a column outside the closed maps, a value other than the planned one, a
+ * namesake id, a second solution, a query beyond the id, a PATCH without exactly the row version the plan holds
+ * (If-Match), a Custom API child PATCH of more than its labels, a publish of a rule the set did not create, a direct
+ * condition, a removal.
+ */
+function createClassifier(entries) {
+ const byId = indexOf(entries);
+ return (req) => classifyWith(byId, req, false);
+}
+
+/**
+ * The same classification for ONE constituent of a $batch change set, for the checked change-set parser
+ * (managed-create-batch.js, a run's `batch` option), exactly as the SDK sends a bound Custom API's edit:
+ * PATCH .../customapis(<bound id>)?$select=customapiid If-Match: <held version> { <editable root fields> }
+ * POST .../customapiresponseproperties?$select=customapiresponsepropertyid { ..., "[email protected]": "/customapis(<bound id>)" }
+ * A root create, a child's label PATCH (admitted only on its own), a membership and a publish are never a constituent.
+ * The descriptor adds what the parser checks a constituent against: `prepared` (the wire body encoded from the plan,
+ * preparedWire), the root's held `ifMatch`, and a seal of the constituent's own wire fields.
+ */
+function classifyConstituent(entries, req) {
+ return constituentOf(indexOf(entries), req);
+}
+
+function constituentOf(byId, req) {
+ const out = classifyWith(byId, req, true);
+ if (!out || out.rows.length !== 1 || !API_KINDS.has(out.rows[0].kind)) return null;
+ const { row } = byId.get(out.rows[0].id);
+ const json = parseBody(req.body).json;
+ const prepared = preparedWire(row, json);
+ if (!prepared || canonicalJson(prepared) !== canonicalJson(json)) return null;
+ // The change-set parser (managed-create-batch.js) compares `prepared` with the constituent key for key, holds the root
+ // PATCH to `ifMatch`, and checks the sealed projection against the constituent's own wire fields — so here the seal is
+ // of every wire key the constituent carries (no private input exists on these kinds), not the semantic projection a
+ // direct request is sealed by.
+ const sealed = { ...out.rows[0], ...sentProjection(json) };
+ return {
+ ...out,
+ rows: [sealed],
+ prepared,
+ ...(row.parentId === null ? { ifMatch: row.ifMatch } : {}),
+ };
+}
+
+// The wire body the plan prepared for one Custom API constituent, key for key over what the constituent carries, each value
+// encoded from the plan's expectation (never copied from the request): the primary key is the planned id, the parent bind
+// names the planned parent, a text or flag is the expected value and an option is its code. A case-insensitive name
+// (a table's logical name) keeps the request's spelling only when it IS the expected name, ignoring case. A key the plan
+// cannot encode makes the whole constituent unprepared (null).
+function preparedWire(row, json) {
+ const k = KINDS[row.kind];
+ const out = {};
+ for (const [key, raw] of Object.entries(json)) {
+ if (key === k.pk) { if (normalizeGuid(raw) !== row.id) return null; out[key] = raw; continue; }
+ const bind = /^(.+)@odata\.bind$/.exec(key);
+ if (bind) {
+ if (!k.parentBind || bind[1] !== k.parentBind || row.parentId === null || boundGuid(raw, k.parentSet) !== row.parentId) return null;
+ out[key] = raw;
+ continue;
+ }
+ const spec = has(k.columns, key) ? k.columns[key] : null;
+ if (!Array.isArray(spec) || !has(row.expected, spec[0])) return null;
+ const want = row.expected[spec[0]];
+ if (spec[1] === lowerText) out[key] = typeof raw === 'string' && typeof want === 'string' && raw.toLowerCase() === want ? raw : want;
+ else if (key === 'type') out[key] = has(PARAM_TYPES, want) ? PARAM_TYPES[want] : null;
+ else if (key === 'bindingtype') out[key] = has(API_BINDINGS, want) ? API_BINDINGS[want] : null;
+ else if (key === 'allowedcustomprocessingsteptype') out[key] = has(API_STEPS, want) ? API_STEPS[want] : null;
+ else out[key] = want;
+ }
+ return out;
+}
+
+/**
+ * The one classifier a run hands the gate (createManagedCreateContext run `classify`) when its set may send the checked
+ * change set: a constituent of a `$batch` (the parser passes its `contentId`) is classified as one (classifyConstituent),
+ * any other request as a direct one (createClassifier).
+ */
+function createSetClassifier(entries) {
+ const byId = indexOf(entries);
+ return (req) => (req && req.contentId !== undefined ? constituentOf(byId, req) : classifyWith(byId, req, false));
+}
+
+module.exports = {
+ NOT_FOUND_CODE,
+ DELETE_CODE,
+ PRIVATE_MISMATCH,
+ KINDS,
+ planOf,
+ declarationSha256Of,
+ artifactFor,
+ acceptResultFor,
+ createClassifier,
+ classifyConstituent,
+ createSetClassifier,
+ readConfigurationRow,
+ readConfigurationConflicts,
+ readComponentTypes,
+ observe,
+ editShapeOf,
+ projectionOf,
+};
diff --git a/plugins/model-apps/scripts/lib/configuration-protected.js b/plugins/model-apps/scripts/lib/configuration-protected.js
new file mode 100644
index 000000000..6f23fd205
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/configuration-protected.js
@@ -0,0 +1,847 @@
+'use strict';
+// Protected configuration (`configurationIdentity: "stable-v1"`): the build side of exact ids and a binding store for the
+// declared environment variables, connection references, Custom APIs and duplicate detection rules.
+//
+// This module is loaded only when the App Spec sets the opt-in, or when the build hands over its binding store without it
+// (configuration-build.js), so a build with neither loads none of the protected modules. It answers four things, the first
+// two through the configuration create driver
+// (configuration-create-bindings.js) and the managed create lifecycle (managed-create-context.js):
+// preflight a whole-plan, read-only pass run before the build changes ANYTHING (the solution, its version, a table):
+// every declared item is located by its binding, never by name, and an edit the protected path cannot
+// make is refused here, so an unsupported edit never leaves the build half applied;
+// port the create port configuration-artifacts.js uses under the opt-in (configurationAcceptsPort): exact-id
+// resolution from the binding store, the mandatory complete namesake query, then one create set run
+// through the send-once gate, observed and settled into the store;
+// verify the same exact location over the workspace's binding store as verify reads it, read-only;
+// opt-out a build without the opt-in whose binding store still holds a declared item stops before any request.
+//
+// The supported shapes are deliberately narrow. A duplicate rule is created with its conditions, completes its initial
+// publication or state, and is then only verified: any later field, condition or state change is refused. A Custom API
+// edit is either one request on its own (the root's editable fields, one new child, or one child's labels) or one
+// checked change set the SDK sends (the root PATCH with new children, or two or more new children); a removal, a change
+// to a child's fixed fields or any other combination is refused.
+
+const B = require('./configuration-create-bindings.js');
+const A = require('./configuration-artifacts.js');
+const { normalizeGuid, isAuthorized, approvalKey } = require('./reconcile-common.js');
+const { hasUnsyncedEdits } = require('./unsynced-edits.js');
+
+const IDENTITY = 'stable-v1';
+const EDIT_CODE = 'configuration-edit-unsupported';
+const UNVERIFIED_CODE = 'create-identity-unverified';
+const CONFLICT_CODE = 'create-identity-conflict';
+const COMPLETION_CODE = 'create-completion-required';
+const OWNERSHIP_CODE = 'create-ownership-required';
+const OPT_IN_CODE = 'create-identity-opt-in-required';
+// A local workspace copy that differs from the server's: the declared views' and charts' stop (sdk-build.js
+// refuseUnsentCopy), with the same way on — keep what you want in the App Spec, then approve replacing the copy.
+const DRAFT_CODE = 'workspace-copy-unsent-edits';
+// The store's own code for a group whose attempt is not settled yet.
+const PENDING_CODE = require('./managed-bindings.js').CODES.pending;
+
+const RULE_EDIT_MESSAGE = 'This protected duplicate rule can be created with its conditions and initial state, then verified. '
+ + 'Later field, condition or state edits are not supported. No service changes were sent by this build. '
+ + 'Make this edit outside the plugin, keeping the binding store and exact ids.';
+const API_EDIT_MESSAGE = 'This protected Custom API change is not a supported single request or create-only changeset. '
+ + 'No service changes were sent by this build. Separate supported non-removing single-request edits across builds, '
+ + 'or make the change outside the plugin. Removals require maintenance outside the plugin.';
+const REMOVAL_MESSAGE = 'Removing a child of a protected Custom API is not supported. No service changes were sent by this build. '
+ + 'Removals require maintenance outside the plugin.';
+const VALUE_REMOVAL_MESSAGE = 'Clearing the value of a protected environment variable deletes its value row, which is not supported. '
+ + 'No service changes were sent by this build. Removals require maintenance outside the plugin.';
+// The one approval that replaces a protected item's local copy with the server's: `--authorize overwrite:<kind>:<key>`,
+// the views' and charts' verb, typed by the configuration kind and keyed as the port keys it (portKeyOf: a name in lower
+// case, a duplicate rule's key byte for byte). build-model-app.js reads it into opts.authorizedOverwrite without its verb
+// (configuration-artifacts.js configurationAuthorizationKeys), so it approves only this item's copy.
+const overwriteKey = (kind, key) => approvalKey(kind, A.portKeyOf(kind, key));
+// Only the exact typed key approves a replacement. The shared isAuthorized also accepts a blanket `true` (an older
+// programmatic form some view callers still pass); here that would discard a protected copy no maker named, so a
+// boolean, or anything that is not a collection of keys, approves nothing.
+const approvesOverwrite = (approved, key) => (approved instanceof Set || Array.isArray(approved)) && isAuthorized(approved, key);
+const draftMessage = (kind, key, id) => `the local copy of the ${kind} "${key}" (${id}) in the workspace differs from the server's (an edit an earlier run did not send, `
+ + 'or one made by hand), or could not be compared; nothing was read over it or written, and the copy was kept. '
+ + 'Put any change you want to keep into the App Spec, then approve replacing the local copy with the server\'s: '
+ + A.authorizeFlags([`overwrite:${overwriteKey(kind, key)}`]);
+
+// The declared lists of the protected kinds, in the order configuration-artifacts.js applies them.
+const LISTS = Object.freeze([
+ ['environmentVariable', 'environmentVariables', 'schemaName'],
+ ['connectionReference', 'connectionReferences', 'logicalName'],
+ ['customApi', 'customApis', 'uniqueName'],
+ ['duplicateRule', 'duplicateDetectionRules', 'key'],
+]);
+const KINDS = new Set(LISTS.map(([kind]) => kind));
+
+const has = (o, k) => !!o && Object.prototype.hasOwnProperty.call(o, k);
+// The deployment-settings bindings (configuration-artifacts.js readDeploymentBindings) hold { value: null } for a clear,
+// keyed by the lower-case schema name — the same key as the variable's plan.
+const clearsValue = (bindings, key) => {
+ const got = bindings && bindings.environmentVariables instanceof Map ? bindings.environmentVariables.get(key) : undefined;
+ return !!got && got.value === null;
+};
+/** The opt-in: exactly `configurationIdentity: "stable-v1"` (app-spec.js refuses any other value). */
+const configurationIdentityOf = (spec) => has(spec, 'configurationIdentity') && spec.configurationIdentity === IDENTITY;
+
+function stop(code, message, extra = {}) {
+ const error = new Error(message);
+ error.code = code;
+ Object.assign(error, extra);
+ return error;
+}
+
+function declaredItems(spec) {
+ const out = [];
+ for (const [kind, list, field] of LISTS) {
+ for (const entry of Array.isArray(spec && spec[list]) ? spec[list] : []) {
+ if (entry && typeof entry[field] === 'string') out.push({ kind, key: entry[field] });
+ }
+ }
+ return out;
+}
+
+// A child record's slot: the driver keys a child row `JSON.stringify([<root key>, <slot>])` (planOf).
+function slotOf(record) {
+ try {
+ const parsed = JSON.parse(record.key);
+ return Array.isArray(parsed) && parsed.length === 2 && typeof parsed[1] === 'string' ? parsed[1] : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Locate one declared item by its binding and plan it, reading only:
+ * { state: 'unbound', planned } no committed binding: a create at the derived ids;
+ * { state: 'pending', planned, token, edit } an attempt is pending (recoverPending decides it from its own expectation);
+ * { state: 'bound', planned } the committed binding, every bound row read fresh at its exact id.
+ * A bound row read absent is `configuration-row-not-found` (never replaced by a namesake), an unreadable one or a binding
+ * whose ids the declaration no longer derives is `create-identity-unverified`; both throw, typed.
+ */
+async function locateItem(env, kind, key) {
+ const { spec, store, dataverse, solution, bindings, componentTypes } = env;
+ const fresh = B.planOf(spec, { kind, key, bindings, solution, componentTypes });
+ const group = store.readGroup(kind, fresh.key);
+ if (group.pending && !group.committed) return { state: 'pending', planned: fresh, token: group.pending.token, edit: false, attempt: group.pending, declaredKey: key };
+ if (!group.committed) return { state: 'unbound', planned: fresh };
+ const records = group.committed.records || [];
+ const root = records.find((r) => r.kind === kind && r.key === fresh.key);
+ if (!root) throw stop(UNVERIFIED_CODE, `the binding of ${kind} "${fresh.key}" holds no root row`, { kind, key: fresh.key });
+ const rootId = normalizeGuid(root.id);
+ const read = async (r) => {
+ const got = await B.readConfigurationRow(dataverse, r.kind, normalizeGuid(r.id));
+ if (got.state === 'absent') throw stop(B.NOT_FOUND_CODE, `the bound ${r.kind} of ${kind} "${fresh.key}" (${normalizeGuid(r.id)}) is gone; it is not replaced by a namesake`, { kind, key: fresh.key, id: normalizeGuid(r.id) });
+ if (got.state !== 'present') throw stop(UNVERIFIED_CODE, `the bound ${r.kind} of ${kind} "${fresh.key}" could not be read`, { kind, key: fresh.key, id: normalizeGuid(r.id) });
+ return got;
+ };
+ const bases = new Map([[rootId, await read(root)]]);
+ // Only the children the declaration still names are bound children of the plan; a bound child it no longer names is
+ // left to the complete child graph (editShapeOf), where it is a removal — never deleted, never adopted. The one
+ // exception is a variable's bound value its deployment settings do not name this run (and do not clear): it is still
+ // the variable's own row, so the plan keeps it at its bound id, sends nothing for it, and an edit of the definition is
+ // not judged a conflict over it. A kept value read absent is no longer there to keep (it was deleted outside the
+ // plugin); nothing is planned for it, and settings that name a value again find its binding gone (not found).
+ const declaredSlots = new Set(fresh.rows.filter((r) => r.slot !== null).map((r) => r.slot));
+ const boundSlots = [];
+ const keptChildren = {};
+ for (const r of records) {
+ if (r === root) continue;
+ const slot = slotOf(r);
+ if (slot === null) continue;
+ if (!declaredSlots.has(slot)) {
+ if (kind !== 'environmentVariable' || slot !== 'value' || clearsValue(bindings, fresh.key)) continue;
+ const got = await B.readConfigurationRow(dataverse, r.kind, normalizeGuid(r.id));
+ if (got.state === 'absent') continue;
+ if (got.state !== 'present') throw stop(UNVERIFIED_CODE, `the bound ${r.kind} of ${kind} "${fresh.key}" could not be read`, { kind, key: fresh.key, id: normalizeGuid(r.id) });
+ keptChildren[slot] = normalizeGuid(r.id);
+ continue;
+ }
+ bases.set(normalizeGuid(r.id), await read(r));
+ boundSlots.push(slot);
+ }
+ const planned = B.planOf(spec, {
+ kind, key, bindings, solution, componentTypes, bases, boundSlots, keptChildren, baseGeneration: group.committed.generation,
+ // Only this item is bound in its own plan: another item of the kind is planned (and judged) on its own.
+ boundIdOf: (k, pk) => (k === kind && pk === fresh.key ? rootId : undefined),
+ });
+ for (const r of records) {
+ const row = planned.rows.find((x) => x.kind === r.kind && x.key === r.key);
+ if (row && row.id !== normalizeGuid(r.id)) throw stop(UNVERIFIED_CODE, `the binding of ${kind} "${fresh.key}" names another ${r.kind} than the declaration derives`, { kind, key: fresh.key });
+ }
+ // A pending EDIT is located like the bound item it edits — at the exact ids its binding holds — and is then decided
+ // from the expectation the attempt itself persisted (recoverPending), never from this plan's.
+ if (group.pending) return { state: 'pending', planned, token: group.pending.token, edit: true, attempt: group.pending, declaredKey: key };
+ return { state: 'bound', planned };
+}
+
+/**
+ * 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);
+ * a Custom API: one request on its own, the root PATCH with one or more new children, or two or more new children only.
+ */
+function editVerdict(kind, shape) {
+ if (kind === 'duplicateRule') {
+ const changed = shape.rootChanged || shape.ruleStateChanged || shape.creates.length || shape.labelEdits.length || shape.fixedEdits.length || shape.removals.length;
+ return changed ? { code: EDIT_CODE, message: RULE_EDIT_MESSAGE } : null;
+ }
+ if (kind !== 'customApi') return null;
+ const root = shape.rootChanged ? 1 : 0;
+ const creates = shape.creates.length;
+ const edits = shape.labelEdits.length;
+ if (shape.removals.length) {
+ return shape.removals.length === 1 && !root && !creates && !edits && !shape.fixedEdits.length
+ ? { code: B.DELETE_CODE, message: REMOVAL_MESSAGE }
+ : { code: EDIT_CODE, message: API_EDIT_MESSAGE };
+ }
+ if (shape.fixedEdits.length) return { code: EDIT_CODE, message: API_EDIT_MESSAGE };
+ if (root + creates + edits <= 1) return null;
+ if (!edits && (root ? creates >= 1 : creates >= 2)) return null;
+ return { code: EDIT_CODE, message: API_EDIT_MESSAGE };
+}
+
+/**
+ * The verdict on a bound environment variable's or connection reference's update, or null when the protected path can
+ * make it (protectedConfigurationPort update: one checked set over the item's complete root/child plan). Read only:
+ * a row under the root that its binding does not hold (a value made outside the plugin) is neither overwritten nor
+ * adopted when this run would write the item — whatever destructive authorization the maker gave, which approves
+ * replacing the item's OWN value, never taking over another row: create-identity-conflict;
+ * a child the update would create (a first value) runs its complete namesake query first: any value already under
+ * the definition is a conflict, and a query that does not complete is create-identity-unverified.
+ * A run that writes nothing for the item (no definition change, no value or connection named) is not judged: a value a
+ * maker set in the environment by hand does not stop a build that leaves the variable alone.
+ */
+async function childVerdict(env, planned, shape) {
+ const { bindings, dataverse } = env;
+ const named = planned.kind === 'environmentVariable'
+ ? !!(bindings && bindings.environmentVariables instanceof Map && bindings.environmentVariables.get(planned.key))
+ : !!(bindings && bindings.connectionReferences instanceof Map && bindings.connectionReferences.get(planned.key));
+ if (!shape.rootChanged && !shape.creates.length && !shape.fixedEdits.length && !named) return null;
+ if (shape.removals.length) {
+ return { code: CONFLICT_CODE, message: `the ${planned.kind} "${planned.key}" has a row under it that its binding does not hold (${shape.removals.join(', ')}); it is neither overwritten nor adopted, and no service changes were sent by this build. Remove or reconcile that row outside the plugin, then run again` };
+ }
+ if (!shape.creates.length) return null;
+ const conflicts = await B.readConfigurationConflicts(dataverse, planned);
+ if (conflicts.state === 'clear') return null;
+ return { code: conflicts.code || UNVERIFIED_CODE, message: `the ${planned.kind} "${planned.key}" namesake query for its new row answered ${conflicts.state}; no service changes were sent by this build` };
+}
+
+/**
+ * The verdict on a first create (an unbound item, or a create proved never applied that is sent again), or null when it
+ * can be made. Read only, the same reads resolve/run make at dispatch, moved before the build's first write:
+ * the root's derived id (exactId): absent is free; a row there that no binding holds is create-identity-conflict (it is
+ * never adopted silently); an answer that is not exact is create-identity-unverified;
+ * the complete namesake query of every row the plan creates (readConfigurationConflicts, every page followed): a
+ * namesake at another id is create-identity-conflict, a query that does not complete is create-identity-unverified.
+ */
+async function firstCreateVerdict(dataverse, planned, { exactId }) {
+ const rootId = planned.plan.rows[0].id;
+ if (exactId) {
+ const read = await B.readConfigurationRow(dataverse, planned.kind, rootId);
+ if (read.state === 'present') return { id: rootId, code: CONFLICT_CODE, message: `the ${planned.kind} "${planned.key}" derived id ${rootId} is taken by a row no binding holds; it is not adopted, and no service changes were sent by this build` };
+ if (read.state !== 'absent') return { id: rootId, code: UNVERIFIED_CODE, message: `the ${planned.kind} "${planned.key}" derived id ${rootId} could not be read; no service changes were sent by this build` };
+ }
+ const conflicts = await B.readConfigurationConflicts(dataverse, planned);
+ if (conflicts.state === 'clear') return null;
+ const ids = conflicts.rows.flatMap((r) => r.ids || []);
+ return {
+ code: conflicts.code || UNVERIFIED_CODE,
+ message: conflicts.state === 'conflict'
+ ? `the ${planned.kind} "${planned.key}" has a namesake at another id (${ids.join(', ')}); a protected create never binds a namesake, and no service changes were sent by this build`
+ : `the ${planned.kind} "${planned.key}" namesake query could not be completed; nothing is created on a read that may have missed a namesake, and no service changes were sent by this build`,
+ };
+}
+
+/**
+ * A pending attempt is decided from its OWN persisted expectation (managed-create-context.js classifyRecovery), read-only,
+ * never re-planned from today's rows. For a create that is what keeps the original plan's completion owed: a duplicate
+ * rule created without an explicit status owes its initial publication, and a rerun after a partial create proves the
+ * rows and that state at the same ids — it commits only when the rule is published (by the original send, or by the
+ * maker under the same id), and it never sends the publication again: an uncertain or failed publish is not replayed,
+ * it stays a create-completion-required halt. The one exception is a publication the attempt's own record proves never
+ * left (unsentPublication): that one is sent once, fenced (publishOnce). A declaration changed since the attempt is
+ * managed-pending-intent-changed.
+ *
+ * A pending EDIT of a bound item is judged the same way, by the attempt's own persisted rows: its declaration digest is
+ * recomputed from today's declaration over THOSE rows (B.declarationSha256Of), and each row is read at its bound id and
+ * compared with the expectation the attempt persisted (observe projects only the field set of the expectation, so
+ * today's values never replace it). A complete edit commits read-only — its PATCH is never repeated; an incomplete or
+ * uncertain one keeps its typed halt. An edit proved unsent (prepared, or sending with nothing dispatched) is resumed
+ * under its own token, ids, parents and generation (`sameRows`: the plan made from today's reads holds exactly the rows
+ * it persisted, so the conditional base read now is the one the resumed send carries); one whose rows no longer match
+ * is retired when only prepared, and otherwise halts until they are restored.
+ * Answers { verdict, observation, declarationSha256?, sameRows? }.
+ */
+async function recoverPending(env, ctx, item) {
+ const { planned } = item;
+ if (!ctx) {
+ return { verdict: { action: 'halt', code: UNVERIFIED_CODE, message: `the ${planned.kind} "${planned.key}" has a pending ${item.edit ? 'edit' : 'attempt'} that this build cannot recover; nothing is sent for it` } };
+ }
+ if (!item.edit) {
+ const observation = await B.observe(env.dataverse, planned);
+ return { observation, verdict: ctx.classify(item.token, observation, { declarationSha256: planned.plan.declarationSha256 }) };
+ }
+ const protocol = item.attempt && item.attempt.rowProtocol;
+ if (!protocol) return { verdict: { action: 'halt', code: UNVERIFIED_CODE, message: `the ${planned.kind} "${planned.key}" pending edit keeps no row expectation; nothing is sent for it` } };
+ const declarationSha256 = B.declarationSha256Of(env.spec, { kind: planned.kind, key: item.declaredKey, solution: planned.solution, rows: protocol.rows, ruleState: protocol.completion.ruleState });
+ const observation = await B.observe(env.dataverse, planned);
+ const verdict = ctx.classify(item.token, observation, { declarationSha256 });
+ return { observation, verdict, declarationSha256, sameRows: sameRows(planned.plan.rows, protocol.rows) };
+}
+
+// A plan row as an attempt persists it (managed-create-context.js buildRowPlan); its row version is not part of it.
+const rowSignature = (r) => JSON.stringify([r.kind, r.key, normalizeGuid(r.id), r.parentId ? normalizeGuid(r.parentId) : null, r.mode, r.expectedSha256, r.sensitiveInput === true]);
+const sameRows = (a, b) => a.length === b.length && a.map(rowSignature).sort().join('\n') === b.map(rowSignature).sort().join('\n');
+
+const pendingEditChanged = (planned) => ({
+ action: 'halt', code: CONFLICT_CODE,
+ message: `the ${planned.kind} "${planned.key}" has an unsent pending edit whose rows changed since it was prepared; nothing is sent for it. `
+ + 'Restore the rows to what they were when the edit was prepared (or make the edit outside the plugin), then run again',
+});
+
+/**
+ * Settle or resume a pending EDIT of a bound item before anything is written for it (resolve), from recoverPending's
+ * answer. The answer is authoritative, never advice the caller may skip:
+ * 'settled' a complete edit committed read-only, or an unsent one whose target is already there (made by hand,
+ * say) ACCEPTED read-only — its own acceptance verdict checked: a refusal throws its typed halt;
+ * 'retired' an unsent one whose rows changed, retired while only prepared;
+ * 'needs-write' an unsent one whose rows match and whose target is not there yet: its write is still owed, and only
+ * update() may send it, resuming the same attempt. The item must never be reported unchanged meanwhile.
+ * Anything else throws a typed halt.
+ */
+async function settlePendingEdit(env, ctx, item, rec) {
+ const { planned } = item;
+ const fail = (verdict) => { const h = haltOf(planned.kind, planned.key, verdict); throw stop(h.code, h.message, h); };
+ if (rec.verdict.action === 'commit') {
+ const [settled] = ctx.settle([{ token: item.token, observation: rec.observation, declarationSha256: rec.declarationSha256 }]);
+ if (settled.verdict.action !== 'commit') fail(settled.verdict);
+ return 'settled';
+ }
+ if (rec.verdict.action !== 'resume') fail(rec.verdict);
+ if (!rec.sameRows) {
+ if (item.attempt.phase !== 'prepared') fail(pendingEditChanged(planned));
+ env.store.retireUnsentAttempt({ token: item.token, baseGeneration: item.attempt.baseGeneration });
+ return 'retired';
+ }
+ if (!readOnlyCandidate(item) || targetMissing(item.attempt.rowProtocol.rows, rec.observation)) return 'needs-write';
+ // Already at its target: accepted with no send. The capture is taken before the fresh read.
+ if (item.attempt.phase === 'prepared') ctx.resume([{ token: item.token, claim: 'first', baseObservation: planned.plan.baseObservation }]);
+ const [capture] = ctx.captureReadOnly([item.token]);
+ const observation = await B.observe(env.dataverse, planned);
+ const [accepted] = ctx.acceptReadOnly([{ token: item.token, observation, capture, declarationSha256: rec.declarationSha256 }]);
+ if (!accepted || accepted.verdict.action !== 'commit') fail(accepted ? accepted.verdict : { code: UNVERIFIED_CODE });
+ return 'settled';
+}
+
+// An edit only a read-only acceptance can settle without a send: every row an update, with the base it was planned over.
+const readOnlyCandidate = (item) => item.attempt.rowProtocol.rows.every((r) => r.mode === 'update') && !!item.planned.plan.baseObservation;
+
+/**
+ * Whether an unsent edit still has its write to make: every row it planned read present, at its own id and parent, and
+ * at least one not at its target yet (its projection differs, or its private input reads different or masked — a masked
+ * value can be proved only by the edit's own send). Anything else is not a write to send: every row at its target is
+ * the read-only acceptance's to judge (an approval it needs, a membership the maker removed), and a row gone, moved or
+ * unreadable is that acceptance's typed halt too. observation: B.observe's { rows: [{ kind, key, state, id, parentId,
+ * projectionSha256, privateState? }] }.
+ */
+function targetMissing(rows, observation) {
+ const seen = new Map(((observation && observation.rows) || []).map((r) => [`${r.kind}\u0000${r.key}`, r]));
+ const read = rows.map((row) => ({ row, at: seen.get(`${row.kind}\u0000${row.key}`) }));
+ const placed = ({ row, at }) => at && at.state === 'present' && normalizeGuid(at.id) === row.id && (at.parentId ? normalizeGuid(at.parentId) : null) === row.parentId;
+ if (!read.length || !read.every(placed)) return false;
+ return read.some(({ row, at }) => at.projectionSha256 !== row.expectedSha256
+ || (row.sensitiveInput === true && (at.privateState === 'mismatch' || at.privateState === 'masked')));
+}
+
+/**
+ * The one completion a pending rule create may still send itself: its initial publication, when the attempt's OWN
+ * record proves that publish never left — the root create acknowledged by its answer (the content was saved), the
+ * plan's `rule-state` effect still `dispatched: false` (the transport seals it dispatched before the request leaves,
+ * so an uncertain, failed or lost publish always reads dispatched), the rule read unpublished, and the attempt
+ * otherwise exactly what it prepared: judged as if the publication had landed, it would commit. Read only. Answers
+ * null when that is not the case (the halt stands), or { would }: the verdict that hypothetical judgement gave — a
+ * commit (the publication is the only thing owed: resolve sends it once), or the halt that would still stand after it
+ * (an ownership approval the maker must give first, named now rather than after the publish).
+ * Never for an edit (a bound rule is never published again), a publish that was or may have been sent, or a rule
+ * whose rows, members or declaration are not exactly the attempt's.
+ */
+function unsentPublication(ctx, item, rec) {
+ const a = item.attempt;
+ const p = a && a.rowProtocol;
+ if (!ctx || item.edit || item.planned.kind !== 'duplicateRule' || !p) return null;
+ const v = rec.verdict;
+ if (v.action !== 'halt' || v.code !== COMPLETION_CODE || v.phase !== 'state-pending') return null;
+ if (a.acknowledgedRoot !== true || p.completion.ruleState !== 'published' || !rec.observation || rec.observation.ruleState !== 'unpublished') return null;
+ const effect = p.effects.find((e) => e.kind === 'rule-state');
+ if (!effect || effect.dispatched) return null;
+ const would = ctx.classify(item.token, { ...rec.observation, ruleState: p.completion.ruleState }, { declarationSha256: item.planned.plan.declarationSha256 });
+ return would.action === 'commit' || would.code === OWNERSHIP_CODE ? { would } : null;
+}
+
+// The publish job is asynchronous: the rule reads Publishing (statecode 0, statuscode 1, neither state) until it ends.
+// The rule's own state is what proves it, so it is read again a bounded number of times (reads only); a rule still not
+// published then keeps its owed state, and a later build commits it once a read finds it published — never sending again.
+const PUBLISH_READS = 10;
+const PUBLISH_READ_INTERVAL_MS = 3000;
+
+/**
+ * Send the publication unsentPublication proved never dispatched, once, through the attempt's fenced create set:
+ * POST /duplicaterules(<id>)/Microsoft.Dynamics.CRM.PublishDuplicateRule {}
+ * claimed first under a new epoch (store.claimUnsentRowEffect), classified as the plan's own rule-state effect and sealed
+ * dispatched before it leaves; then the attempt is observed and settled. Answers the settled verdict.
+ * See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/publishduplicaterule
+ */
+async function publishOnce(env, ctx, item) {
+ const { planned } = item;
+ const id = planned.plan.rows[0].id;
+ const attempt = ctx.claimEffect(item.token, { kind: 'rule-state', id });
+ const classify = B.createSetClassifier([{ token: attempt.token, planned }]);
+ const sent = await ctx.run({ attempts: [attempt], classify, deleteCode: B.DELETE_CODE, label: `configuration publish duplicateRule ${planned.key}` },
+ () => env.dataverse.post(`/duplicaterules(${id})/Microsoft.Dynamics.CRM.PublishDuplicateRule`, {}));
+ let observation = await B.observe(env.dataverse, planned);
+ // Only a publish the service accepted (a 2xx answer) is waited for; a refused or unanswered one is judged by this one
+ // read (it may still have been applied: a read that finds the rule published proves it, and nothing is ever sent
+ // again either way).
+ const accepted = !sent.error && !sent.localError
+ && ctx.facts(item.token).some((f) => f.type === 'effect' && f.kind === 'rule-state' && f.outcome === 'acknowledged');
+ for (let i = 1; accepted && observation.ruleState !== 'published' && i < PUBLISH_READS; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise((r) => setTimeout(r, PUBLISH_READ_INTERVAL_MS));
+ // eslint-disable-next-line no-await-in-loop
+ observation = await B.observe(env.dataverse, planned);
+ }
+ const [settled] = ctx.settle([{ token: item.token, observation, declarationSha256: planned.plan.declarationSha256 }]);
+ return settled.verdict;
+}
+
+const haltOf = (kind, key, verdict) => ({
+ kind, key, ...(verdict.rows && verdict.rows[0] ? { id: verdict.rows[0].id } : {}), code: verdict.code || UNVERIFIED_CODE, message: verdict.message || `the ${kind} "${key}" could not be recovered`,
+ ...(Array.isArray(verdict.approvals) && verdict.approvals.length ? { approvals: verdict.approvals.slice() } : {}),
+});
+
+// What every protected read needs, read once per build: the solution's component types (membership is planned only
+// outside the restricted solutions, but the read is cheap and fail-closed).
+async function environmentOf({ spec, store, dataverse, solution, bindings }) {
+ const types = await B.readComponentTypes(dataverse);
+ if (!types || !types.complete) throw stop(UNVERIFIED_CODE, 'the solution component types could not be read');
+ return { spec, store, dataverse, solution, bindings, componentTypes: types.types };
+}
+
+/**
+ * Replace a protected item's local copy with the server's, under the maker's overwrite approval only (the preflight checks
+ * it). The server's row is read directly first: present → the SDK's overwrite fetch; absent (a create the service never
+ * took) → the local copy is deleted, since there is no server copy to put in its place. Any other answer — a denied or
+ * failed read, a read of another row — or a failed fetch/delete answers false and the caller keeps the copy and halts: a
+ * fetch error cannot tell a missing row from a failed read (the SDK reports a remote 404 as a connection error).
+ */
+async function replaceLocalCopy(dataverse, sdk, kind, id) {
+ try {
+ const row = await B.readConfigurationRow(dataverse, kind, id);
+ if (row.state === 'present') {
+ await sdk.fetchArtifact(kind, id, { overwrite: true });
+ return !(await hasUnsyncedEdits(sdk, kind, id));
+ }
+ if (row.state !== 'absent') return false;
+ await sdk.deleteArtifact(kind, id);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * The whole-plan, read-only preflight: every declared protected item located by its binding and its edit judged — a
+ * bound Custom API or duplicate rule by its supported shapes (editVerdict), a bound environment variable or connection
+ * reference by its complete root/child plan (childVerdict), a bound variable's value clear is a removal and refused, and a
+ * first create (unbound, or proved never applied) by its derived id and its complete namesake query (firstCreateVerdict).
+ * Sends nothing. Answers { halts: [{ kind, key, id?, code, message }] } — empty when
+ * the build may continue. A read that cannot be completed is a halt (`create-identity-unverified`), never "no change".
+ */
+async function preflightProtectedConfiguration({ spec, store, ctx, dataverse, solution, bindings, sdk = null, authorizedOverwrite = null }) {
+ if (!configurationIdentityOf(spec)) return { halts: [] };
+ const halts = [];
+ let env;
+ try {
+ env = await environmentOf({ spec, store, dataverse, solution, bindings });
+ } catch (error) {
+ return { halts: [{ kind: 'configuration', key: '*', code: error.code || UNVERIFIED_CODE, message: error.message }] };
+ }
+ for (const { kind, key } of declaredItems(spec)) {
+ try {
+ const item = await locateItem(env, kind, key);
+ // Every later step of a bound or pending item reads its row into the workspace over the local copy (locate's
+ // overwrite fetch); a copy with edits the service has not seen stops it first, kept. The proofs above and below
+ // read the service directly (B.readConfigurationRow / B.observe), never the workspace copy.
+ // The copy is replaced only under the maker's exact overwrite approval for this item, never by the build on its
+ // own (a failed send included): a diff says that the copy differs, never whose the difference is.
+ if (item.state !== 'unbound' && sdk) {
+ const id = item.planned.plan.rows[0].id;
+ if (await hasUnsyncedEdits(sdk, kind, id)) {
+ if (!approvesOverwrite(authorizedOverwrite, overwriteKey(kind, item.planned.key))) {
+ halts.push({ kind, key: item.planned.key, id, code: DRAFT_CODE, message: draftMessage(kind, item.planned.key, id), overwrite: `overwrite:${overwriteKey(kind, item.planned.key)}` });
+ continue;
+ }
+ if (!(await replaceLocalCopy(env.dataverse, sdk, kind, id))) {
+ halts.push({ kind, key: item.planned.key, id, code: DRAFT_CODE, message: `the local copy of the ${kind} "${item.planned.key}" (${id}) could not be replaced with the server's as approved, because the server's row could not be read exactly; the local copy was kept and nothing was written. Run again` });
+ continue;
+ }
+ }
+ }
+ if (item.state === 'pending') {
+ const rec = await recoverPending(env, ctx, item);
+ if (rec.verdict.action === 'halt') {
+ // A saved rule create whose initial publication provably never left: resolve sends it once (unsentPublication).
+ const owed = unsentPublication(ctx, item, rec);
+ if (owed && owed.would.action === 'commit') continue;
+ halts.push(haltOf(kind, item.planned.key, owed ? owed.would : rec.verdict));
+ continue;
+ }
+ // A complete edit settles read-only (resolve): nothing more is written for it, so it is not judged as an edit.
+ if (!item.edit) {
+ // A create proved never applied is sent again at its own ids (run), after the same namesake query a first create runs.
+ if (rec.verdict.action === 'resume') { const v = await firstCreateVerdict(env.dataverse, item.planned, { exactId: false }); if (v) halts.push({ kind, key: item.planned.key, ...v }); }
+ continue;
+ }
+ if (rec.verdict.action === 'commit') continue;
+ if (!rec.sameRows && item.attempt.phase !== 'prepared') { halts.push(haltOf(kind, item.planned.key, pendingEditChanged(item.planned))); continue; }
+ // An unsent edit whose target is already there is not sent: resolve accepts it read-only. That acceptance is judged
+ // now, so a refusal (an approval it needs, a membership removed by hand) stops the build before anything is sent.
+ if (rec.sameRows && readOnlyCandidate(item) && !targetMissing(item.attempt.rowProtocol.rows, rec.observation)) {
+ const [judged] = ctx.judgeReadOnly([{ token: item.token, observation: rec.observation, declarationSha256: rec.declarationSha256 }]);
+ if (judged.verdict.action !== 'commit') halts.push(haltOf(kind, item.planned.key, judged.verdict));
+ continue;
+ }
+ // An unsent edit is judged below like the bound item it edits: it is what this build would send.
+ } else if (item.state === 'unbound') {
+ // A first create: its reserved ids and its namesakes are judged here, before the build's first write (the solution
+ // version PATCH included), so a create that cannot be made stops the build with nothing sent. resolve/run check
+ // both again at dispatch, since a row can appear between this read and the create.
+ const verdict = await firstCreateVerdict(env.dataverse, item.planned, { exactId: true });
+ if (verdict) halts.push({ kind, key: item.planned.key, ...verdict });
+ continue;
+ } else if (item.state !== 'bound') continue;
+ // Clearing a bound variable's value (a deployment-settings Value of null) is a DELETE of its value row, a physical
+ // 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; }
+ // 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)
+ : await childVerdict(env, item.planned, shape);
+ if (verdict) halts.push({ kind, key: item.planned.key, ...verdict });
+ } catch (error) {
+ halts.push({ kind, key, ...(error.id ? { id: error.id } : {}), code: error.code || UNVERIFIED_CODE, message: error.message });
+ }
+ }
+ return { halts };
+}
+
+// The members a planned create still owes the solution, added in the create set's own scope (the classifier admits only
+// the planned memberships): POST /AddSolutionComponent { ComponentId, ComponentType, SolutionUniqueName, AddRequiredComponents }.
+async function addMissingMembers(dataverse, planned, scope) {
+ const seen = await B.observe(dataverse, planned);
+ const missing = seen.members.filter((m) => m.state === 'absent').map((m) => planned.plan.members.find((x) => x.id === m.id)).filter(Boolean);
+ if (!missing.length) return { localError: null, error: null };
+ return scope(async () => {
+ for (const m of missing) {
+ // eslint-disable-next-line no-await-in-loop
+ await dataverse.post('/AddSolutionComponent', { ComponentId: m.id, ComponentType: m.componentType, SolutionUniqueName: planned.solution, AddRequiredComponents: false });
+ }
+ });
+}
+
+/**
+ * The create port configuration-artifacts.js uses for the protected kinds (configurationAcceptsPort accepts it):
+ * protects(kind) the four configuration kinds;
+ * resolve({ kind, key }) { state: 'present', id } for a bound item (read at its exact id) — with `owed`
+ * ({ code, message }) when an unsent pending edit of it still owes its write, which
+ * only update() sends — or
+ * { state: 'absent', id } with the derived id when nothing is bound and that id is
+ * free; anything else throws, typed — never a name lookup;
+ * run({ kind, key }, fn) the mandatory complete namesake query, then ONE create set: fn({ id, childIds })
+ * pushes the artifact through the gate, the members are added, and the attempt is
+ * observed and settled into the store. Answers { outcome: 'created', id, childIds,
+ * result } only for a committed create; anything else throws, typed;
+ * exact true: configuration-artifacts.js skips its name lookup for a protected kind;
+ * updates(kind) true for a Custom API, an environment variable and a connection reference, whose
+ * supported edits go through update();
+ * update({ kind, key, id }, fn) ONE checked set for a bound item's edit the preflight admitted: fn({ childIds })
+ * makes the SDK's element updates and ONE push (one request, or one checked
+ * change set when apiBase is known, refused unsent otherwise), new children are
+ * added to the solution, and the attempt is observed and settled. Answers
+ * { outcome: 'updated', id, childIds, result }; anything else throws, typed.
+ */
+function protectedConfigurationPort({ spec, store, ctx, dataverse, solution, bindings, apiBase = null, sdk = null }) {
+ let envPromise = null;
+ const env = () => (envPromise = envPromise || environmentOf({ spec, store, dataverse, solution, bindings }));
+ // A send this port ran that did not settle (a throw, a refused push, an answer that never came) leaves the workspace copy
+ // exactly as it is: the build's own change, and any edit a maker wrote meanwhile through the same workspace. The copy is
+ // shared with the maker and the SDK has no operation that compares it and replaces it in one step, so no check made
+ // before a reset can prove the reset discards only the build's own change; the build therefore never resets it. The
+ // attempt is still recovered read-only from what it persisted (recoverPending), and the next build's preflight stops on
+ // the copy (DRAFT_CODE) until the maker keeps what they want and approves replacing it with the server's
+ // (--authorize overwrite:<kind>:<key>, overwriteKey).
+ return {
+ // The binding store is the authority on these kinds: locate asks this port before any other record (configuration-artifacts.js).
+ exact: true,
+ protects: (kind) => KINDS.has(kind),
+ async resolve({ kind, key }) {
+ const item = await locateItem(await env(), kind, key);
+ const rootId = item.planned.plan.rows[0].id;
+ if (item.state === 'bound') return { state: 'present', id: rootId };
+ if (item.state === 'pending' && item.edit) {
+ // The edit's bound row is there whatever the attempt's fate: settle (or retire) the attempt first, so the item is
+ // planned from a settled binding. An edit whose write is still owed is left for update() to resume, and says so:
+ // the plan may never count it unchanged (configuration-artifacts.js planOne) while its attempt is pending.
+ const settled = await settlePendingEdit(await env(), ctx, item, await recoverPending(await env(), ctx, item));
+ if (settled === 'needs-write') {
+ return { state: 'present', id: rootId, owed: { code: COMPLETION_CODE, message: `the ${kind} "${item.planned.key}" has an unsent pending edit whose write is still owed; only that edit is sent for it` } };
+ }
+ return { state: 'present', id: rootId };
+ }
+ if (item.state === 'pending') {
+ const rec = await recoverPending(await env(), ctx, item);
+ let { verdict } = rec;
+ const { observation } = rec;
+ if (verdict.action === 'commit') {
+ // The earlier create is complete as it was planned: commit it, then it is this build's bound row.
+ const [settled] = ctx.settle([{ token: item.token, observation, declarationSha256: item.planned.plan.declarationSha256 }]);
+ if (settled.verdict.action === 'commit') return { state: 'present', id: rootId };
+ const h = haltOf(kind, item.planned.key, settled.verdict);
+ throw stop(h.code, h.message, h);
+ }
+ // Nothing the attempt sent can have been applied: it is created again, under the same ids (run resumes it).
+ if (verdict.action === 'resume') return { state: 'absent', id: rootId };
+ // A saved rule create whose initial publication provably never left: sent once, fenced, then settled.
+ const owed = unsentPublication(ctx, item, rec);
+ if (owed) verdict = owed.would.action === 'commit' ? await publishOnce(await env(), ctx, item) : owed.would;
+ if (verdict.action === 'commit') return { state: 'present', id: rootId };
+ const h = haltOf(kind, item.planned.key, verdict);
+ throw stop(h.code, h.message, h);
+ }
+ const read = await B.readConfigurationRow(dataverse, kind, rootId);
+ if (read.state === 'absent') return { state: 'absent', id: rootId };
+ // A row at the derived id that no binding holds is not adopted silently: adoption needs its own approval.
+ throw stop(read.state === 'present' ? CONFLICT_CODE : UNVERIFIED_CODE, `the ${kind} "${item.planned.key}" derived id is ${read.state === 'present' ? 'taken by a row no binding holds' : 'unreadable'}`, { kind, key: item.planned.key, id: rootId });
+ },
+ async run({ kind, key }, fn) {
+ const item = await locateItem(await env(), kind, key);
+ let resumed = null;
+ if (item.state === 'pending' && !item.edit) {
+ const { verdict } = await recoverPending(await env(), ctx, item);
+ if (verdict.action !== 'resume') throw stop(UNVERIFIED_CODE, `the ${kind} "${item.planned.key}" pending attempt is not one to send again`, { kind, key: item.planned.key });
+ resumed = { token: item.token, claim: verdict.claim };
+ } else if (item.state !== 'unbound') {
+ throw stop(UNVERIFIED_CODE, `the ${kind} "${item.planned.key}" is not a create`, { kind, key: item.planned.key });
+ }
+ const { planned } = item;
+ const conflicts = await B.readConfigurationConflicts(dataverse, planned);
+ if (conflicts.state !== 'clear') throw stop(conflicts.code || UNVERIFIED_CODE, `the ${kind} "${planned.key}" namesake query answered ${conflicts.state}`, { kind, key: planned.key });
+ const [attempt] = resumed ? ctx.resume([resumed]) : ctx.begin([planned.plan]);
+ const classify = B.createSetClassifier([{ token: attempt.token, planned }]);
+ const label = `configuration create ${kind} ${planned.key}`;
+ const scope = (send, acceptResult) => ctx.run({ attempts: [attempt], classify, deleteCode: B.DELETE_CODE, label, acceptResult }, send);
+ const id = planned.plan.rows[0].id;
+ const childIds = Object.fromEntries(planned.rows.filter((r) => r.slot !== null).map((r) => [r.slot, r.id]));
+ const pushed = await scope(() => fn({ id, childIds }), B.acceptResultFor(planned));
+ // An operation refused before its first request (nothing counted, nothing dispatched) leaves no attempt behind;
+ // one that may have sent anything keeps it for recovery (ctx.release refuses it). The stop below stands either way.
+ if (!pushed.checked) ctx.release(attempt);
+ if (pushed.error) throw pushed.error;
+ if (pushed.localError) throw stop(pushed.localError.code || UNVERIFIED_CODE, String(pushed.localError.message || pushed.localError), { kind, key: planned.key, id });
+ if (!pushed.checked) throw stop('create-outcome-unknown', `the ${kind} "${planned.key}" create was not acknowledged`, { kind, key: planned.key, id });
+ const added = await addMissingMembers(dataverse, planned, scope);
+ if (added.error || added.localError) throw stop('create-outcome-unknown', `the ${kind} "${planned.key}" solution membership was not acknowledged`, { kind, key: planned.key, id });
+ const [settled] = ctx.settle([{ token: attempt.token, observation: await B.observe(dataverse, planned) }]);
+ if (settled.verdict.action !== 'commit') throw stop(settled.verdict.code || UNVERIFIED_CODE, settled.verdict.message || `the ${kind} "${planned.key}" create was not proved`, { kind, key: planned.key, id });
+ return { outcome: 'created', id, childIds, result: pushed.value };
+ },
+ /**
+ * A bound item's edit (configuration-artifacts.js applyUpdate) — a Custom API, an environment variable (its definition,
+ * a first value or a replacement of its own value) or a connection reference: the plan is made again from fresh reads
+ * of the bound rows at their exact ids (never a name), and `fn({ childIds })` — the SDK's own element updates
+ * and ONE push — runs inside that plan's create set: a single request on its own, or the one checked change set the
+ * SDK sends for the root PATCH with new children or for new children only (`batch`). The new children take the plan's
+ * derived ids (`childIds`); the set's classifier admits a write only to a row the plan holds, so a value the SDK found
+ * under the definition at another id is never PATCHed. Answers { outcome: 'updated', id,
+ * childIds, result } only for a committed edit; anything else throws, typed. The build's preflight has already refused
+ * every shape the protected path cannot make, before anything was sent.
+ */
+ updates: (kind) => kind === 'customApi' || kind === 'environmentVariable' || kind === 'connectionReference',
+ async update({ kind, key, id }, fn) {
+ const item = await locateItem(await env(), kind, key);
+ const { planned } = item;
+ const at = (item.state === 'bound' || (item.state === 'pending' && item.edit)) && planned.plan.rows[0].id === normalizeGuid(id);
+ if (!at) throw stop(UNVERIFIED_CODE, `the ${kind} "${planned.key}" is not bound at ${normalizeGuid(id)}`, { kind, key: planned.key });
+ let resumed = null;
+ if (item.state === 'pending') {
+ // Only an edit proved unsent whose rows are still the ones it persisted is sent again, under its own token.
+ const rec = await recoverPending(await env(), ctx, item);
+ if (rec.verdict.action !== 'resume') { const h = haltOf(kind, planned.key, rec.verdict); throw stop(h.code, h.message, h); }
+ if (!rec.sameRows) { const h = haltOf(kind, planned.key, pendingEditChanged(planned)); throw stop(h.code, h.message, h); }
+ resumed = { token: item.token, claim: rec.verdict.claim, baseObservation: planned.plan.baseObservation || null };
+ }
+ if (planned.rows.some((r) => r.mode === 'create')) {
+ const conflicts = await B.readConfigurationConflicts(dataverse, planned);
+ if (conflicts.state !== 'clear') throw stop(conflicts.code || UNVERIFIED_CODE, `the ${kind} "${planned.key}" namesake query answered ${conflicts.state}`, { kind, key: planned.key });
+ }
+ const [attempt] = resumed ? ctx.resume([resumed]) : ctx.begin([planned.plan]);
+ const classify = B.createSetClassifier([{ token: attempt.token, planned }]);
+ const label = `configuration edit ${kind} ${planned.key}`;
+ const batch = apiBase ? { batch: { apiBase, solution: planned.solution } } : {};
+ const scope = (send, acceptResult) => ctx.run({ attempts: [attempt], classify, deleteCode: B.DELETE_CODE, label, acceptResult, ...batch }, send);
+ const childIds = Object.fromEntries(planned.rows.filter((r) => r.slot !== null && r.mode === 'create').map((r) => [r.slot, r.id]));
+ const rootId = planned.plan.rows[0].id;
+ const pushed = await scope(() => fn({ childIds }), B.acceptResultFor(planned));
+ // As in run(): an edit the SDK refused before its first request — a Custom API label edit on an environment with
+ // more than one language (CUSTOM_API_LABELS_UNSUPPORTED) — is released, so the next build plans from the committed
+ // group whatever it declares; kept, it held the group for a declaration that is never sent.
+ if (!pushed.checked) ctx.release(attempt);
+ if (pushed.error) throw pushed.error;
+ if (pushed.localError) throw stop(pushed.localError.code || UNVERIFIED_CODE, String(pushed.localError.message || pushed.localError), { kind, key: planned.key, id: rootId });
+ if (!pushed.checked) throw stop('create-outcome-unknown', `the ${kind} "${planned.key}" edit was not acknowledged`, { kind, key: planned.key, id: rootId });
+ const added = await addMissingMembers(dataverse, planned, scope);
+ if (added.error || added.localError) throw stop('create-outcome-unknown', `the ${kind} "${planned.key}" solution membership was not acknowledged`, { kind, key: planned.key, id: rootId });
+ const [settled] = ctx.settle([{ token: attempt.token, observation: await B.observe(dataverse, planned) }]);
+ if (settled.verdict.action !== 'commit') throw stop(settled.verdict.code || UNVERIFIED_CODE, settled.verdict.message || `the ${kind} "${planned.key}" edit was not proved`, { kind, key: planned.key, id: rootId });
+ return { outcome: 'updated', id: rootId, childIds, result: pushed.value };
+ },
+ };
+}
+
+/**
+ * The binding store's own debt, read before ANY service change of a build — whatever the App Spec declares today, with or
+ * without the opt-in, whichever phases run: every unfinished attempt (or unusable group) of a protected configuration kind
+ * whose item the App Spec no longer declares. Omitting a declaration never lets a build go on past what an earlier one left
+ * pending: its rows may exist and its effects may be owed, and only its own declaration can settle it. Nothing is retired,
+ * deleted or reset here, and a committed group the App Spec dropped is not debt (its rows simply stay). A declared item is
+ * judged by the protected preflight (or, without the opt-in, by optInObligations), so it is not listed twice.
+ * A local store read only: nothing is sent. Answers { halts: [{ kind, key, code, message }] }.
+ */
+function pendingSweep({ spec, store }) {
+ if (!store || typeof store.snapshot !== 'function') return { halts: [] };
+ if (typeof store.refresh === 'function') store.refresh();
+ const declared = new Set(declaredItems(spec || {}).map(({ kind, key }) => `${kind}\u0000${A.portKeyOf(kind, key)}`));
+ const halts = [];
+ for (const unit of store.snapshot().units()) {
+ if (!KINDS.has(unit.family) || !(unit.attempt || unit.invalid) || declared.has(`${unit.family}\u0000${unit.key}`)) continue;
+ const what = unit.attempt ? 'an unfinished attempt' : 'a record it cannot use';
+ halts.push({ kind: unit.family, key: unit.key, code: PENDING_CODE, message: `the binding store holds ${what} for ${unit.family} "${unit.key}", which this App Spec no longer declares. `
+ + 'Restore its declaration, with configurationIdentity "stable-v1", so a build can settle it, then run again. No service changes were sent by this build.' });
+ }
+ return { halts };
+}
+
+/**
+ * The build's configuration hookup: what the build calls with the binding store, the send-once gate bound to it and the
+ * managed create context over both, once a protected feature is selected. Answers { preflight, port, obligations, sweep }:
+ * preflight runs the read-only whole-plan pass, port is the create port the configuration runtime installs, obligations is
+ * the local store read a build without the opt-in runs (optInObligations), and sweep is the store-driven debt read every
+ * build runs before its first service change (pendingSweep). Nothing here creates a gate or a store: the build owns them.
+ */
+function createProtectedConfiguration({ store, gate, ctx, apiBase = null } = {}) {
+ if (!store || typeof store.readGroup !== 'function') throw new TypeError('createProtectedConfiguration needs the managed binding store');
+ if (!ctx || typeof ctx.begin !== 'function' || typeof ctx.run !== 'function' || typeof ctx.settle !== 'function') throw new TypeError('createProtectedConfiguration needs the managed create context');
+ return {
+ store,
+ gate,
+ ctx,
+ preflight: ({ spec, dataverse, solution, bindings, sdk, authorizedOverwrite }) => preflightProtectedConfiguration({ spec, store, ctx, dataverse, solution, bindings, sdk, authorizedOverwrite }),
+ port: ({ spec, dataverse, solution, bindings, sdk }) => protectedConfigurationPort({ spec, store, ctx, dataverse, solution, bindings, apiBase, sdk }),
+ // A build without the opt-in: what the store still holds for its declared items (optInObligations), read locally.
+ obligations: ({ spec }) => optInObligations({ spec, store }),
+ // Every build, before its first service change: what the store still owes for items the App Spec no longer declares.
+ sweep: ({ spec }) => pendingSweep({ spec, store }),
+ };
+}
+
+/**
+ * The obligations a build WITHOUT the opt-in still owes the binding store (`create-identity-opt-in-required`): every
+ * declared item of the protected kinds whose group in the store is committed, pending or unusable. Removing
+ * `configurationIdentity` does not move a protected item back to name lookup — a namesake could then stand in for its
+ * bound row — so the build stops before any request and asks for the opt-in back. A local store read only: nothing is
+ * sent. An item the store holds nothing for is not an obligation, so an App Spec that never opted in builds as before.
+ * Answers { halts: [{ kind, key, code, message }] }.
+ */
+function optInObligations({ spec, store }) {
+ if (configurationIdentityOf(spec) || !store || typeof store.readGroup !== 'function') return { halts: [] };
+ const halts = [];
+ for (const { kind, key } of declaredItems(spec)) {
+ let held;
+ try {
+ const group = store.readGroup(kind, A.portKeyOf(kind, key));
+ held = !!(group.committed || group.pending);
+ } catch {
+ // A group the store cannot use is state this build cannot rule out: still an obligation.
+ held = true;
+ }
+ if (held) {
+ halts.push({ kind, key, code: OPT_IN_CODE, message: `the binding store holds protected configuration for ${kind} "${key}", and configurationIdentity "stable-v1" was removed. `
+ + 'Removing it does not move a protected item back to name lookup: restore configurationIdentity "stable-v1". No service changes were sent by this build.' });
+ }
+ }
+ return { halts };
+}
+
+// Verify's read-only view of the binding store: the workspace's managedManifestView (declared-form-io.js readVerifyManifest),
+// answered in the shape locateItem reads (readGroup). A pending attempt has no token here: verify never recovers one.
+// No view at all, an unusable store or an unusable group proves nothing, so it is create-identity-unverified, never "unbound".
+function manifestStore(manifest) {
+ const view = manifest && Array.isArray(manifest.groups) ? manifest : null;
+ return {
+ readGroup(family, key) {
+ if (!view) throw stop(UNVERIFIED_CODE, 'no binding store was read for this verify; a protected item is never verified by name', { kind: family, key });
+ if ((view.invalid || []).some((u) => u && (u.family === 'store' || (u.family === family && u.key === key)))) {
+ throw stop(UNVERIFIED_CODE, `the binding store's record of ${family} "${key}" is not usable`, { kind: family, key });
+ }
+ const pending = (view.pending || []).some((p) => p && p.family === family && p.key === key);
+ const group = view.groups.find((g) => g && g.family === family && g.key === key);
+ return { committed: group ? { records: group.records, generation: group.generation } : null, pending: pending ? { token: null } : null };
+ },
+ };
+}
+
+/**
+ * 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
+ * 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);
+ * create-identity-unverified no committed binding, no usable store, or a read that did not complete.
+ */
+function protectedVerifyPort({ spec, manifest, dataverse, solution, bindings }) {
+ const store = manifestStore(manifest);
+ let envPromise = null;
+ const env = () => (envPromise = envPromise || environmentOf({ spec, store, dataverse, solution, bindings }));
+ return {
+ exact: true,
+ 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 };
+ 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 });
+ },
+ // configuration-artifacts.js takes a port by its `run`; verify never creates, so this one refuses unsent.
+ async run({ kind, key }) {
+ throw stop(UNVERIFIED_CODE, `verify sends nothing: the ${kind} "${key}" is not created here`, { kind, key });
+ },
+ };
+}
+
+module.exports = {
+ EDIT_CODE,
+ OPT_IN_CODE,
+ RULE_EDIT_MESSAGE,
+ API_EDIT_MESSAGE,
+ configurationIdentityOf,
+ editVerdict,
+ optInObligations,
+ pendingSweep,
+ preflightProtectedConfiguration,
+ protectedConfigurationPort,
+ protectedVerifyPort,
+ createProtectedConfiguration,
+};
diff --git a/plugins/model-apps/scripts/lib/managed-bindings.js b/plugins/model-apps/scripts/lib/managed-bindings.js
index d40fe28e7..123594522 100644
--- a/plugins/model-apps/scripts/lib/managed-bindings.js
+++ b/plugins/model-apps/scripts/lib/managed-bindings.js
@@ -40,7 +40,13 @@ const { withRecordLease } = require('./record-lease.js');
const { redactOutput } = require('./output-redaction.js');
const PREFIX = 'managed-bindings.';
+// The envelope version. A store that holds only the original families stays at 1, exactly as an older build writes
+// it; the first write that adds a group or attempt of a ROW_FAMILY (the configuration families, `configurationIdentity:
+// "stable-v1"`) writes 2 in the same atomic change, and a version-2 store stays at 2. An older build refuses a
+// version-2 file at this boundary, so it never reads a row protocol it does not know; resetting or deleting the file
+// is not a downgrade (its bindings and pending obligations would be lost).
const SCHEMA_VERSION = 1;
+const SCHEMA_VERSION_ROWS = 2;
// The whole file, as written (indented JSON). A larger file is refused, never truncated: on read it is unreadable, and a
// write that would make one is `managed-binding-store-full` with nothing written.
// Sized for the declarations the file keeps. A group can hold its declaration up to three times: the committed
@@ -136,16 +142,43 @@ const CODES = Object.freeze({
// `completionBytes`) may be, once the unreserved bytes are gone. Remedy: keep fewer or smaller declared groups in one
// app and solution, or settle the pending ones first.
storeFull: 'managed-binding-store-full',
+ // A configuration request that its attempt's row protocol does not allow (a row it did not prepare under that id, a
+ // second send of a row or effect): refused before the request leaves.
+ requestMismatch: 'managed-create-request-mismatch',
});
-const FAMILIES = ['form', 'dashboard', 'rule', 'bpf', 'view', 'chart'];
+// The configuration families (lib/configuration-create-bindings.js): one group per declared environment variable,
+// connection reference, Custom API or duplicate-detection rule, holding its root and its own child rows. They exist only
+// in a version-2 store and keep the row protocol (validateRowProtocol) on their attempts.
+const ROW_FAMILIES = Object.freeze(['environmentVariable', 'connectionReference', 'customApi', 'duplicateRule']);
+const FAMILIES = ['form', 'dashboard', 'rule', 'bpf', 'view', 'chart', ...ROW_FAMILIES];
// Forms and dashboards are rows of one table (systemform), rules and process flows of another (workflow): a root id
// may be bound once per table, whichever family claims it.
-const NAMESPACE = { form: 'systemform', dashboard: 'systemform', rule: 'workflow', bpf: 'workflow', view: 'savedquery', chart: 'savedqueryvisualization' };
+const NAMESPACE = {
+ form: 'systemform', dashboard: 'systemform', rule: 'workflow', bpf: 'workflow', view: 'savedquery', chart: 'savedqueryvisualization',
+ environmentVariable: 'environmentvariabledefinition', connectionReference: 'connectionreference', customApi: 'customapi', duplicateRule: 'duplicaterule',
+};
+// The physical table of each row kind a row family binds, root and child: a row id may be bound once per table across
+// every group (an alias check by the record's own table, not its root family's).
+const ROW_TABLE = Object.freeze({
+ environmentVariable: 'environmentvariabledefinition', environmentVariableValue: 'environmentvariablevalue',
+ connectionReference: 'connectionreference',
+ customApi: 'customapi', customApiRequestParameter: 'customapirequestparameter', customApiResponseProperty: 'customapiresponseproperty',
+ duplicateRule: 'duplicaterule', duplicateRuleCondition: 'duplicaterulecondition',
+});
+// The child kinds each row family may hold under its root.
+const ROW_CHILD_KINDS = Object.freeze({
+ environmentVariable: ['environmentVariableValue'], connectionReference: [],
+ customApi: ['customApiRequestParameter', 'customApiResponseProperty'], duplicateRule: ['duplicateRuleCondition'],
+});
+const ROW_PROOF_SCHEMA = 'configuration-rows-v1';
// The binding kind of each family's root record. It is the kind the create catalog (lib/creates-catalog.js) hands a
// feature, so a feature records its root under the same spelling it was given: a business rule's group family is the
// short `rule`, but its root is a `business-rule` binding, never a `rule` one.
-const ROOT_KIND = Object.freeze({ form: 'form', dashboard: 'dashboard', rule: 'business-rule', bpf: 'bpf', view: 'view', chart: 'chart' });
+const ROOT_KIND = Object.freeze({
+ form: 'form', dashboard: 'dashboard', rule: 'business-rule', bpf: 'bpf', view: 'view', chart: 'chart',
+ environmentVariable: 'environmentVariable', connectionReference: 'connectionReference', customApi: 'customApi', duplicateRule: 'duplicateRule',
+});
const PUBLISHING = new Set(['form', 'dashboard', 'view', 'chart']);
const PUBLICATION_STATES = new Set(['not-needed', 'owed', 'dispatching', 'unconfirmed', 'confirmed']);
// `fulfilled` is a state change this attempt never sent whose desired state a fresh read found already on its row: a
@@ -163,6 +196,7 @@ const CONSUMER_KEYS = {
bpf: ['declaration', 'stages'],
view: ['baseline'],
chart: ['baseline'],
+ ...Object.fromEntries(ROW_FAMILIES.map((f) => [f, ['version', 'rows']])),
};
// The fixed control id of a form's timeline; it repeats on every form that has one, so it is not a physical alias.
const NOTES_CONTROL = 'notescontrol';
@@ -198,13 +232,15 @@ function guidField(v, where) {
if (typeof v !== 'string' || normalizeGuid(v) !== v) throw invalid(where, 'is not a lowercase GUID');
}
+// The closed vocabulary of a publish scope, by its type. Shared with checkRowExtensions.
+const SCOPE_KEYS = Object.freeze({ table: ['type', 'table'], dashboard: ['type', 'id'] });
function validateScope(scope, where) {
if (!isObj(scope)) throw invalid(where, 'is not a scope');
if (scope.type === 'table') {
- closedKeys(scope, ['type', 'table'], where);
+ closedKeys(scope, SCOPE_KEYS.table, where);
if (!/^[a-z0-9_]+$/.test(String(scope.table))) throw invalid(where, 'names no table');
} else if (scope.type === 'dashboard') {
- closedKeys(scope, ['type', 'id'], where);
+ closedKeys(scope, SCOPE_KEYS.dashboard, where);
guidField(scope.id, `${where}.id`);
} else {
throw invalid(where, 'is not a table or dashboard scope');
@@ -416,8 +452,9 @@ function checkDeclaration(family, key, declaration) {
}
}
+const ROOT_KEYS = ['kind', 'key', 'id'];
function validateRoot(root, family, key, where) {
- closedKeys(root, ['kind', 'key', 'id'], where);
+ closedKeys(root, ROOT_KEYS, where);
if (!nonempty(root.kind) || root.key !== key) throw invalid(where, 'is not this group\'s root');
guidField(root.id, `${where}.id`);
if (root.kind !== ROOT_KIND[family]) throw invalid(where, `is a ${root.kind} root, and a ${family} group's root is a ${ROOT_KIND[family]}`);
@@ -435,10 +472,28 @@ function validateProof(proof, where) {
}
}
+// The closed field vocabulary of each persisted shape. The validators hold every unit to it, and checkRowExtensions
+// holds a configuration unit to it BEFORE that unit's own validation can isolate it (see there).
+const RECORD_KEYS = ['formatVersion', 'appUniqueName', 'environmentFingerprint', 'kind', 'key', 'id', 'intentSha256', 'origin', 'parentKey', 'partsSha256', 'localCreateDraft'];
+const GROUP_KEYS = ['family', 'key', 'generation', 'previousGeneration', 'root', 'proofSchema', 'records', 'proof', 'consumerState', 'originalDeclaration', 'publication'];
+const ATTEMPT_KEYS = ['family', 'key', 'token', 'baseGeneration', 'phase', 'root', 'knownScopes', 'declarationSha256', 'declaration', 'expected', 'acknowledgedRoot', 'acknowledgedChildCreates', 'savedObservation', 'publication', 'sendWindow', 'completionReserve', 'dashboardCreate', 'rowProtocol'];
+const EXPECTED_KEYS = ['proofVersion', 'proofSchema', 'rootId', 'baseProofSha256', 'sentProjectionSha256', 'preservationSha256', 'baseObservation', 'children'];
+const EXPECTED_CHILD_KEYS = ['kind', 'key', 'namespaceParentId', 'id', 'associationSha256'];
+const BASE_OBSERVATION_KEYS = ['rowVersion', 'savedSha256'];
+const SAVED_OBSERVATION_KEYS = ['phase', 'proof', 'acknowledgedRoot'];
+const CHILD_RECEIPT_KEYS = ['kind', 'key', 'id'];
+const PUBLICATION_KEYS = ['scope', 'state', 'desiredSha256', 'dispatchToken', 'carriedFrom'];
+const ATTEMPT_PUBLICATION_KEYS = ['scope', 'state'];
+// A carried publication's `carriedFrom`: the current shape, and the older one (only state and dispatch token).
+const CARRIED_FROM_KEYS = ['state', 'dispatchToken', 'publishedSha256', 'savedSha256'];
+const LEGACY_CARRIED_FROM_KEYS = ['state', 'dispatchToken'];
+const SEND_WINDOW_KEYS = ['possible', 'notStarted', 'epoch'];
+const COMPLETION_RESERVE_KEYS = ['bytes', 'used'];
+
function validateRecord(rec, header, where) {
// `localCreateDraft` is placed only by the store (commitGroup) and only on a created dashboard root; validateGroup
// checks where it sits (validateLocalCreateDraft).
- closedKeys(rec, ['formatVersion', 'appUniqueName', 'environmentFingerprint', 'kind', 'key', 'id', 'intentSha256', 'origin', 'parentKey', 'partsSha256', 'localCreateDraft'], where);
+ closedKeys(rec, RECORD_KEYS, where);
if (rec.formatVersion !== 1) throw invalid(where, 'has an unknown format');
if (rec.appUniqueName !== header.appUniqueName || rec.environmentFingerprint !== header.environmentFingerprint) throw invalid(where, 'belongs to another app or environment');
if (!nonempty(rec.kind) || !nonempty(rec.key)) throw invalid(where, 'has no kind or key');
@@ -482,10 +537,10 @@ function validatePublication(pub, family, where, { attempt = false } = {}) {
}
if (attempt) {
if (pub === null) return;
- closedKeys(pub, ['scope', 'state'], where);
+ closedKeys(pub, ATTEMPT_PUBLICATION_KEYS, where);
if (pub.state !== 'owed') throw invalid(where, 'is not owed');
} else {
- closedKeys(pub, ['scope', 'state', 'desiredSha256', 'dispatchToken', 'carriedFrom'], where);
+ closedKeys(pub, PUBLICATION_KEYS, where);
if (!PUBLICATION_STATES.has(pub.state)) throw invalid(where, 'has an unknown state');
hashOrNull(pub.desiredSha256, `${where}.desiredSha256`);
// A dispatch token is written only in the branch that actually sends, so it exists exactly when a send may have run.
@@ -501,14 +556,14 @@ function validatePublication(pub, family, where, { attempt = false } = {}) {
const cf = pub.carriedFrom;
const w = `${where}.carriedFrom`;
if (isObj(cf) && ('publishedSha256' in cf || 'savedSha256' in cf)) {
- closedKeys(cf, ['state', 'dispatchToken', 'publishedSha256', 'savedSha256'], w);
+ closedKeys(cf, CARRIED_FROM_KEYS, w);
hashOrNull(cf.publishedSha256, `${w}.publishedSha256`, false);
hashOrNull(cf.savedSha256, `${w}.savedSha256`, false);
if (cf.state === 'confirmed') tokenField(cf.dispatchToken, `${w}.dispatchToken`);
else if ((cf.state !== 'not-needed' && cf.state !== 'owed') || cf.dispatchToken !== null) throw invalid(w, 'is not a publication a publish can carry');
} else {
if (typeof pub.desiredSha256 !== 'string') throw invalid(where, 'is carried with no desired hash to confirm');
- closedKeys(cf, ['state', 'dispatchToken'], w);
+ closedKeys(cf, LEGACY_CARRIED_FROM_KEYS, w);
if (cf.state === 'confirmed') tokenField(cf.dispatchToken, `${w}.dispatchToken`);
else if (cf.state !== 'not-needed' || cf.dispatchToken !== null) throw invalid(w, 'is not a settled publication');
}
@@ -520,7 +575,7 @@ function validatePublication(pub, family, where, { attempt = false } = {}) {
}
function validateExpected(exp, where) {
- closedKeys(exp, ['proofVersion', 'proofSchema', 'rootId', 'baseProofSha256', 'sentProjectionSha256', 'preservationSha256', 'baseObservation', 'children'], where);
+ closedKeys(exp, EXPECTED_KEYS, where);
if (exp.proofVersion !== 1) throw invalid(where, 'has an unknown proof version');
if (!nonempty(exp.proofSchema)) throw invalid(where, 'names no proof schema');
guidField(exp.rootId, `${where}.rootId`);
@@ -528,7 +583,7 @@ function validateExpected(exp, where) {
hashOrNull(exp.sentProjectionSha256, `${where}.sentProjectionSha256`, false);
hashOrNull(exp.preservationSha256, `${where}.preservationSha256`, false);
if (exp.baseObservation !== null) {
- closedKeys(exp.baseObservation, ['rowVersion', 'savedSha256'], `${where}.baseObservation`);
+ closedKeys(exp.baseObservation, BASE_OBSERVATION_KEYS, `${where}.baseObservation`);
if (exp.baseObservation.rowVersion !== null && !nonempty(exp.baseObservation.rowVersion)) throw invalid(`${where}.baseObservation`, 'has an empty row version');
hashOrNull(exp.baseObservation.savedSha256, `${where}.baseObservation.savedSha256`);
}
@@ -536,7 +591,7 @@ function validateExpected(exp, where) {
const seen = new Set();
exp.children.forEach((c, i) => {
const w = `${where}.children[${i}]`;
- closedKeys(c, ['kind', 'key', 'namespaceParentId', 'id', 'associationSha256'], w);
+ closedKeys(c, EXPECTED_CHILD_KEYS, w);
if (!nonempty(c.kind) || !nonempty(c.key) || !nonempty(c.id)) throw invalid(w, 'is incomplete');
if (c.kind === 'business-rule-node') throw invalid(w, 'expects a business-rule node');
guidField(c.namespaceParentId, `${w}.namespaceParentId`);
@@ -548,7 +603,7 @@ function validateExpected(exp, where) {
}
function validateGroup(g, header, where) {
- closedKeys(g, ['family', 'key', 'generation', 'previousGeneration', 'root', 'proofSchema', 'records', 'proof', 'consumerState', 'originalDeclaration', 'publication'], where);
+ closedKeys(g, GROUP_KEYS, where);
tokenField(g.generation, `${where}.generation`);
tokenField(g.previousGeneration, `${where}.previousGeneration`, true);
validateRoot(g.root, g.family, g.key, `${where}.root`);
@@ -558,6 +613,11 @@ function validateGroup(g, header, where) {
g.records.forEach((r, i) => { if (r.localCreateDraft !== undefined) validateLocalCreateDraft(g, r, `${where}.records[${i}].localCreateDraft`); });
validateProof(g.proof, `${where}.proof`);
closedKeys(g.consumerState, CONSUMER_KEYS[g.family], `${where}.consumerState`);
+ if (isRowFamily(g.family)) {
+ if (g.proofSchema !== ROW_PROOF_SCHEMA) throw invalid(where, `names the proof schema ${g.proofSchema}, not ${ROW_PROOF_SCHEMA}`);
+ for (const rec of g.records) if (!rowKindAllowed(g.family, rec.kind)) throw invalid(where, `binds a ${rec.kind} row, which a ${g.family} group does not hold`);
+ validateRowConsumer(g.consumerState, g.family, g.records, `${where}.consumerState`);
+ }
validateConsumerValue(g.consumerState, `${where}.consumerState`);
// The original declaration of the attempt that committed this generation, when it recorded one: kept beside the
// feature's consumer state, never inside it (a feature's derived state is checked by the stricter rule above).
@@ -617,12 +677,12 @@ function validateLocalCreateDraft(g, rec, where) {
}
function validateAttempt(a, where) {
- closedKeys(a, ['family', 'key', 'token', 'baseGeneration', 'phase', 'root', 'knownScopes', 'declarationSha256', 'declaration', 'expected', 'acknowledgedRoot', 'acknowledgedChildCreates', 'savedObservation', 'publication', 'sendWindow', 'completionReserve', 'dashboardCreate'], where);
+ closedKeys(a, ATTEMPT_KEYS, where);
// The completion reservation (prepareAttempt; see COMPLETION_BASE_BYTES), e.g. { bytes: 434176, used: 1290 }. Absent
// on an attempt an older build prepared: it holds nothing until a new send under it acquires one (markSending, as an
// admission); an attempt already sent with none (read-only recovery, a commit) uses only unreserved bytes.
if (a.completionReserve !== undefined) {
- closedKeys(a.completionReserve, ['bytes', 'used'], `${where}.completionReserve`);
+ closedKeys(a.completionReserve, COMPLETION_RESERVE_KEYS, `${where}.completionReserve`);
const { bytes, used } = a.completionReserve;
if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > COMPLETION_MAX_BYTES || !Number.isSafeInteger(used) || used < 0 || used > bytes) throw invalid(`${where}.completionReserve`, 'is not a reservation');
}
@@ -647,7 +707,7 @@ function validateAttempt(a, where) {
}
if (typeof a.acknowledgedRoot !== 'boolean') throw invalid(where, 'has no acknowledged-root flag');
if (a.savedObservation !== null) {
- closedKeys(a.savedObservation, ['phase', 'proof', 'acknowledgedRoot'], `${where}.savedObservation`);
+ closedKeys(a.savedObservation, SAVED_OBSERVATION_KEYS, `${where}.savedObservation`);
if (!PHASES.has(a.savedObservation.phase) || typeof a.savedObservation.acknowledgedRoot !== 'boolean') throw invalid(`${where}.savedObservation`, 'is incomplete');
validateConsumerValue(a.savedObservation.proof, `${where}.savedObservation.proof`);
}
@@ -668,12 +728,24 @@ function validateAttempt(a, where) {
// more at every claim to continue or resume it (markSending `claim`). A dispatch counted under any
// other epoch is refused unsent (noteAttemptDispatch), so an older run is fenced at the transport.
if (a.sendWindow !== undefined) {
- closedKeys(a.sendWindow, ['possible', 'notStarted', 'epoch'], `${where}.sendWindow`);
+ closedKeys(a.sendWindow, SEND_WINDOW_KEYS, `${where}.sendWindow`);
for (const k of ['possible', 'notStarted']) if (!Number.isSafeInteger(a.sendWindow[k]) || a.sendWindow[k] < 0) throw invalid(`${where}.sendWindow.${k}`, 'is not a count');
if (!Number.isSafeInteger(a.sendWindow.epoch) || a.sendWindow.epoch < 1) throw invalid(`${where}.sendWindow.epoch`, 'is not an epoch');
if (a.phase === 'prepared') throw invalid(where, 'has a send window but was never marked sending');
}
if (a.dashboardCreate !== undefined) validateDashboardCreate(a, `${where}.dashboardCreate`);
+ // The row protocol: required on every attempt of a configuration family, refused on any other.
+ if (isRowFamily(a.family)) {
+ if (a.rowProtocol === undefined) throw invalid(where, 'has no row protocol');
+ validateRowProtocol(a.rowProtocol, a, `${where}.rowProtocol`);
+ if (a.expected) {
+ if (a.expected.proofSchema !== ROW_PROOF_SCHEMA) throw invalid(where, `expects the proof schema ${a.expected.proofSchema}, not ${ROW_PROOF_SCHEMA}`);
+ for (const c of a.expected.children) {
+ const row = a.rowProtocol.rows.find((r) => r.kind === c.kind && r.key === c.key);
+ if (!row || row.id !== rowIdKey(c.id)) throw invalid(where, `expects the ${c.kind} "${c.key}" its row protocol does not name under that id`);
+ }
+ }
+ } else if (a.rowProtocol !== undefined) throw invalid(where, 'keeps a row protocol its family has no place for');
}
// The workflow effects the attempt `a` owns.
@@ -728,9 +800,29 @@ function attemptProvenUnsent(a, effects) {
if (a.dashboardCreate && a.dashboardCreate.acknowledged) return false;
const w = a.sendWindow;
if (!w || w.possible !== 0) return false;
+ // A row or completion effect marked dispatched may have reached the service even when no generic counter moved.
+ if (a.rowProtocol && (a.rowProtocol.rows.some((r) => r.dispatched) || a.rowProtocol.effects.some((e) => e.dispatched))) return false;
return ownedEffects(a, effects).every((x) => (x.state === 'definitely-unsent' || x.state === 'fulfilled') && x.dispatchToken === null);
}
+/**
+ * What a read-only acceptance (commitReadOnlyGroupSet) is checked against, captured BEFORE the fresh read that proves
+ * the rows: { token, generation, epoch, digest } of the attempt `token` in `envelope` — its group's generation (null
+ * when none is committed), its send window epoch (null when it has none) and the sha256 of the attempt, its group and
+ * every workflow effect it owns, so any write to any of them between the capture and the acceptance refuses it.
+ * Answers null when the envelope holds no such attempt.
+ */
+function readOnlyCapture(envelope, token) {
+ const a = envelope && Array.isArray(envelope.attempts) ? envelope.attempts.find((x) => x.token === token) : null;
+ if (!a) return null;
+ const group = envelope.groups.find((g) => g.family === a.family && g.key === a.key) || null;
+ const effects = (envelope.workflowEffects || []).filter((e) => e.attemptToken === token);
+ return {
+ token, generation: group ? group.generation : null, epoch: a.sendWindow ? a.sendWindow.epoch : null,
+ digest: sha256(canonicalJson({ attempt: a, group, effects })),
+ };
+}
+
/**
* May the attempt be resumed as a create (runManagedFeature's `resumeCreate`)? Only when its record says it was a create
* of a new root and that no answer ever acknowledged it: no committed group and no base generation, an expected proof
@@ -805,7 +897,7 @@ function validateChildReceipt(list, a, where) {
const rootId = rowIdKey(a.root.id);
list.forEach((c, i) => {
const w = `${where}[${i}]`;
- closedKeys(c, ['kind', 'key', 'id'], w);
+ closedKeys(c, CHILD_RECEIPT_KEYS, w);
if (!nonempty(c.kind) || !nonempty(c.key) || !nonempty(c.id)) throw invalid(w, 'is incomplete');
const id = rowIdKey(c.id);
if ((c.kind === a.root.kind && c.key === a.root.key) || id === rootId) throw invalid(w, 'names the root, which only a root create acknowledges');
@@ -817,6 +909,221 @@ function validateChildReceipt(list, a, where) {
});
}
+// ---------------------------------------------------------------------------------------------
+// The row protocol of the configuration families (ROW_FAMILIES). An attempt of one of them carries, besides the
+// common expected proof, one closed record of every physical row it creates or edits, written BEFORE anything is sent:
+// rowProtocol: {
+// version: 1,
+// rows: [{ kind, key, id, parentId, mode: 'create' | 'update', expectedSha256, sensitiveInput,
+// sentFields: null | ['<field>', ...], sentSha256: null | '<sha256>', dispatched }],
+// preserved: [], // foreign rows a command bar keeps; none for configuration
+// completion: { ruleState: null | 'published' | 'unpublished', members: [{ kind, id, componentType }] },
+// effects: [{ kind: 'membership' | 'rule-state', id, dispatched }],
+// cohort: null,
+// }
+// `expectedSha256` is the semantic row the plan expects (never a private value or its digest; `sensitiveInput` only
+// says the row carries one). `sentFields`/`sentSha256` are the non-private projection of the request that actually
+// left, sealed with `dispatched: true` under the lease before the transport is called (sealRowDispatch); a sealed row
+// is never sealed again, so a second request for it is refused unsent. `completion.ruleState` is the rule state the
+// ORIGINAL plan wanted (a new rule's default included), so a retry never reinterprets it from the row as it now looks.
+const ROW_PROTOCOL_KEYS = ['version', 'rows', 'preserved', 'completion', 'effects', 'cohort'];
+const ROW_KEYS = ['kind', 'key', 'id', 'parentId', 'mode', 'expectedSha256', 'sensitiveInput', 'sentFields', 'sentSha256', 'dispatched'];
+const ROW_COMPLETION_KEYS = ['ruleState', 'members'];
+const ROW_MEMBER_KEYS = ['kind', 'id', 'componentType'];
+const ROW_EFFECT_KEYS = ['kind', 'id', 'dispatched'];
+const ROW_CONSUMER_ROW_KEYS = ['kind', 'key', 'id', 'parentId', 'projectionSha256', 'sensitiveInput'];
+const ROW_EFFECT_KINDS = new Set(['membership', 'rule-state']);
+const isRowFamily = (family) => ROW_FAMILIES.includes(family);
+const rowKindAllowed = (family, kind) => kind === ROOT_KIND[family] || (ROW_CHILD_KINDS[family] || []).includes(kind);
+const FIELD_NAME = /^[A-Za-z_][A-Za-z0-9_@.]{0,127}$/;
+
+function validateRowProtocol(p, a, where) {
+ closedKeys(p, ROW_PROTOCOL_KEYS, where);
+ if (p.version !== 1) throw invalid(where, 'has an unknown row protocol version');
+ if (!Array.isArray(p.rows) || p.rows.length === 0) throw invalid(where, 'names no row');
+ const keys = new Set();
+ const ids = new Set();
+ p.rows.forEach((r, i) => {
+ const w = `${where}.rows[${i}]`;
+ closedKeys(r, ROW_KEYS, w);
+ for (const k of ROW_KEYS) if (!Object.prototype.hasOwnProperty.call(r, k)) throw invalid(w, `has no ${k}`);
+ if (!rowKindAllowed(a.family, r.kind)) throw invalid(w, `is a ${r.kind} row, which a ${a.family} group does not hold`);
+ if (!nonempty(r.key)) throw invalid(w, 'has no key');
+ guidField(r.id, `${w}.id`);
+ if (r.parentId !== null) guidField(r.parentId, `${w}.parentId`);
+ if (r.mode !== 'create' && r.mode !== 'update') throw invalid(w, 'has an unknown mode');
+ hashOrNull(r.expectedSha256, `${w}.expectedSha256`, false);
+ if (typeof r.sensitiveInput !== 'boolean' || typeof r.dispatched !== 'boolean') throw invalid(w, 'has no sensitive-input or dispatched flag');
+ if (r.sentFields === null) {
+ if (r.sentSha256 !== null || r.dispatched) throw invalid(w, 'is dispatched without the request it sent');
+ } else {
+ if (!Array.isArray(r.sentFields) || !r.sentFields.every((f) => typeof f === 'string' && FIELD_NAME.test(f))) throw invalid(w, 'has unreadable sent fields');
+ if (r.sentFields.some((f, j) => j > 0 && r.sentFields[j - 1] >= f)) throw invalid(w, 'has sent fields that are not sorted and unique');
+ hashOrNull(r.sentSha256, `${w}.sentSha256`, false);
+ if (!r.dispatched) throw invalid(w, 'keeps a sealed request it never dispatched');
+ }
+ if (a.phase === 'prepared' && r.dispatched) throw invalid(w, 'was dispatched before its attempt was marked sending');
+ const k = `${r.kind}\u0000${r.key}`;
+ if (keys.has(k) || ids.has(r.id)) throw invalid(w, 'repeats a row');
+ keys.add(k);
+ ids.add(r.id);
+ });
+ const root = p.rows.find((r) => r.kind === a.root.kind && r.key === a.root.key);
+ if (!root || root.id !== a.root.id || root.parentId !== null) throw invalid(where, 'does not name the attempt\'s root as its top-level row');
+ p.rows.forEach((r, i) => {
+ if (r !== root && r.parentId !== root.id) throw invalid(`${where}.rows[${i}]`, 'is not a child of the attempt\'s root');
+ });
+ if (!Array.isArray(p.preserved) || p.preserved.length) throw invalid(where, 'preserves rows a configuration group never holds');
+ closedKeys(p.completion, ROW_COMPLETION_KEYS, `${where}.completion`);
+ if (p.completion.ruleState !== null && !(a.family === 'duplicateRule' && (p.completion.ruleState === 'published' || p.completion.ruleState === 'unpublished'))) {
+ throw invalid(`${where}.completion`, 'has a rule state for something that is not a duplicate rule');
+ }
+ if (a.family === 'duplicateRule' && p.completion.ruleState === null) throw invalid(`${where}.completion`, 'has no rule state for a duplicate rule');
+ if (!Array.isArray(p.completion.members)) throw invalid(`${where}.completion`, 'has no member list');
+ const members = new Set();
+ p.completion.members.forEach((m, i) => {
+ const w = `${where}.completion.members[${i}]`;
+ closedKeys(m, ROW_MEMBER_KEYS, w);
+ guidField(m.id, `${w}.id`);
+ if (!p.rows.some((r) => r.kind === m.kind && r.id === m.id)) throw invalid(w, 'is not a row of this attempt');
+ if (!Number.isSafeInteger(m.componentType) || m.componentType <= 0) throw invalid(w, 'has no component type');
+ if (members.has(m.id)) throw invalid(w, 'repeats a member');
+ members.add(m.id);
+ });
+ if (!Array.isArray(p.effects)) throw invalid(where, 'has no effect list');
+ const effects = new Set();
+ p.effects.forEach((e, i) => {
+ const w = `${where}.effects[${i}]`;
+ closedKeys(e, ROW_EFFECT_KEYS, w);
+ if (!ROW_EFFECT_KINDS.has(e.kind)) throw invalid(w, 'has an unknown kind');
+ guidField(e.id, `${w}.id`);
+ if (typeof e.dispatched !== 'boolean') throw invalid(w, 'has no dispatched flag');
+ if (a.phase === 'prepared' && e.dispatched) throw invalid(w, 'was dispatched before its attempt was marked sending');
+ if (e.kind === 'membership' && !members.has(e.id)) throw invalid(w, 'adds a member the completion does not name');
+ if (e.kind === 'rule-state' && (a.family !== 'duplicateRule' || e.id !== a.root.id)) throw invalid(w, 'changes the state of another row than its rule');
+ const k = `${e.kind}\u0000${e.id}`;
+ if (effects.has(k)) throw invalid(w, 'repeats an effect');
+ effects.add(k);
+ });
+ // Configuration items are independent groups; only the command bar (not shipped by this store version) keeps cohorts.
+ if (p.cohort !== null) throw invalid(where, 'names a cohort, which a configuration group never joins');
+}
+
+// What a committed configuration group keeps as consumer state: the last confirmed semantic baseline of each row,
+// { version: 1, rows: [{ kind, key, id, parentId, projectionSha256, sensitiveInput }] }
+// It grants no ownership of its own (the records do) and never holds a value, a connection id or a digest of either.
+function validateRowConsumer(state, family, records, where) {
+ closedKeys(state, CONSUMER_KEYS[family], where);
+ if (state.version !== 1) throw invalid(where, 'has an unknown version');
+ if (!Array.isArray(state.rows)) throw invalid(where, 'has no rows');
+ const seen = new Set();
+ state.rows.forEach((r, i) => {
+ const w = `${where}.rows[${i}]`;
+ closedKeys(r, ROW_CONSUMER_ROW_KEYS, w);
+ if (!rowKindAllowed(family, r.kind) || !nonempty(r.key)) throw invalid(w, 'is not a row of this family');
+ guidField(r.id, `${w}.id`);
+ if (r.parentId !== null) guidField(r.parentId, `${w}.parentId`);
+ hashOrNull(r.projectionSha256, `${w}.projectionSha256`, false);
+ if (typeof r.sensitiveInput !== 'boolean') throw invalid(w, 'has no sensitive-input flag');
+ if (!records.some((rec) => rec.kind === r.kind && rec.key === r.key && rowIdKey(rec.id) === r.id)) throw invalid(w, 'is a row the group does not bind');
+ const k = `${r.kind}\u0000${r.key}`;
+ if (seen.has(k)) throw invalid(w, 'repeats a row');
+ seen.add(k);
+ });
+}
+
+// The version and vocabulary of a configuration unit, checked BEFORE its own validation and outside the catch that
+// isolates one invalid unit (parseEnvelope). A known-format unit that is merely wrong (a field missing or mistyped, a
+// hash that is not one) is isolated like any other; but a protocol, consumer, record or proof version this build does
+// not know, a proof schema it does not know, or a field outside the closed vocabulary of the unit or of any closed shape
+// nested in it (a root, a proof, a record and its create evidence, the consumer state and its rows, a publication and
+// its scope, the expected proof, the saved observation, the send window, the completion reservation, the dashboard
+// create receipt, the row protocol and its rows, completion and effects) is what a NEWER plugin writes. The open values
+// (a saved observation's proof, a declaration, a record's partsSha256 map) have no closed vocabulary to check.
+// Isolating such a unit would let this build write the rest of the file around a unit it cannot read, and a later
+// write of its own would then carry that unit forward as this build understood it. So the whole store is refused
+// (managed-binding-store-unreadable), on open, on refresh and on the reread inside every write, and no sibling unit
+// (a form, a view) can be written either. Nothing is discarded: a compatible plugin reads the file as it was.
+// Only numbers and strings are compared here: a version or schema of the wrong type is a malformed unit, not a newer one.
+function checkRowExtensions(x, unit, where) {
+ if (!isRowFamily(x.family)) return;
+ const newer = (w, why) => invalid(w, `${why}: it was written by a newer plugin, so the whole store is refused`);
+ const closed = (obj, allowed, w) => {
+ if (!isObj(obj)) return;
+ for (const k of Object.keys(obj)) if (!allowed.includes(k)) throw newer(w, `has the unknown field "${k}"`);
+ };
+ const each = (list, allowed, w) => { if (Array.isArray(list)) list.forEach((v, i) => closed(v, allowed, `${w}[${i}]`)); };
+ const version = (obj, field, w) => {
+ if (isObj(obj) && typeof obj[field] === 'number' && obj[field] !== 1) throw newer(w, `has ${field} ${obj[field]}`);
+ };
+ const schema = (obj, w) => {
+ if (isObj(obj) && typeof obj.proofSchema === 'string' && obj.proofSchema !== ROW_PROOF_SCHEMA) throw newer(w, `names the proof schema ${obj.proofSchema}`);
+ };
+ // A scope of a type this build knows is held to that type's vocabulary; a type it does not know is a malformed scope.
+ // Only a string type is looked up: a persisted type is untrusted, and using any other value as a property key would
+ // coerce it (an object such as { "toString": null } throws a raw TypeError there, before the per-unit catch). A
+ // missing or mistyped type is left to validateScope, which isolates the unit.
+ const scope = (s, w) => {
+ if (isObj(s) && typeof s.type === 'string' && Object.prototype.hasOwnProperty.call(SCOPE_KEYS, s.type)) closed(s, SCOPE_KEYS[s.type], w);
+ };
+ // A configuration family is never published, so its publication is null; one that is not is held to the vocabulary
+ // anyway, because a field this build does not know there is still what a newer plugin writes.
+ const publication = (pub, w, keys) => {
+ if (!isObj(pub)) return;
+ closed(pub, keys, w);
+ scope(pub.scope, `${w}.scope`);
+ if (isObj(pub.carriedFrom)) closed(pub.carriedFrom, CARRIED_FROM_KEYS, `${w}.carriedFrom`);
+ };
+ if (unit === 'group') {
+ closed(x, GROUP_KEYS, where);
+ schema(x, where);
+ closed(x.root, ROOT_KEYS, `${where}.root`);
+ closed(x.proof, PROOF_KEYS, `${where}.proof`);
+ each(x.records, RECORD_KEYS, `${where}.records`);
+ if (Array.isArray(x.records)) {
+ x.records.forEach((r, i) => {
+ version(r, 'formatVersion', `${where}.records[${i}]`);
+ if (isObj(r)) {
+ closed(r.localCreateDraft, LOCAL_CREATE_DRAFT_KEYS, `${where}.records[${i}].localCreateDraft`);
+ version(r.localCreateDraft, 'formatVersion', `${where}.records[${i}].localCreateDraft`);
+ }
+ });
+ }
+ closed(x.consumerState, CONSUMER_KEYS[x.family], `${where}.consumerState`);
+ version(x.consumerState, 'version', `${where}.consumerState`);
+ if (isObj(x.consumerState)) each(x.consumerState.rows, ROW_CONSUMER_ROW_KEYS, `${where}.consumerState.rows`);
+ publication(x.publication, `${where}.publication`, PUBLICATION_KEYS);
+ return;
+ }
+ closed(x, ATTEMPT_KEYS, where);
+ closed(x.root, ROOT_KEYS, `${where}.root`);
+ if (Array.isArray(x.knownScopes)) x.knownScopes.forEach((s, i) => scope(s, `${where}.knownScopes[${i}]`));
+ closed(x.sendWindow, SEND_WINDOW_KEYS, `${where}.sendWindow`);
+ closed(x.completionReserve, COMPLETION_RESERVE_KEYS, `${where}.completionReserve`);
+ closed(x.dashboardCreate, DASHBOARD_CREATE_KEYS, `${where}.dashboardCreate`);
+ version(x.dashboardCreate, 'formatVersion', `${where}.dashboardCreate`);
+ publication(x.publication, `${where}.publication`, ATTEMPT_PUBLICATION_KEYS);
+ const exp = x.expected;
+ closed(exp, EXPECTED_KEYS, `${where}.expected`);
+ version(exp, 'proofVersion', `${where}.expected`);
+ schema(exp, `${where}.expected`);
+ if (isObj(exp)) {
+ closed(exp.baseObservation, BASE_OBSERVATION_KEYS, `${where}.expected.baseObservation`);
+ each(exp.children, EXPECTED_CHILD_KEYS, `${where}.expected.children`);
+ }
+ closed(x.savedObservation, SAVED_OBSERVATION_KEYS, `${where}.savedObservation`);
+ each(x.acknowledgedChildCreates, CHILD_RECEIPT_KEYS, `${where}.acknowledgedChildCreates`);
+ const p = x.rowProtocol;
+ closed(p, ROW_PROTOCOL_KEYS, `${where}.rowProtocol`);
+ version(p, 'version', `${where}.rowProtocol`);
+ if (isObj(p)) {
+ each(p.rows, ROW_KEYS, `${where}.rowProtocol.rows`);
+ each(p.effects, ROW_EFFECT_KEYS, `${where}.rowProtocol.effects`);
+ closed(p.completion, ROW_COMPLETION_KEYS, `${where}.rowProtocol.completion`);
+ if (isObj(p.completion)) each(p.completion.members, ROW_MEMBER_KEYS, `${where}.rowProtocol.completion.members`);
+ }
+}
+
// The frozen workflow mutation shapes (lib/workflow-effect-context.js classifies requests into them), with the method
// each is sent with and the effects it may carry.
const REQUEST_SHAPES = Object.freeze({
@@ -1067,7 +1374,7 @@ function parseEnvelope(text, expect) {
throw storeError(CODES.unreadable, `the managed binding store is not valid JSON (${e.message})`);
}
closedKeys(data, ['schemaVersion', 'environmentFingerprint', 'appUniqueName', 'solutionUniqueName', 'revision', 'groups', 'attempts', 'workflowEffects', 'publicationRiskAcceptances', 'retiredGroups', 'incarnations'], 'the managed binding store');
- if (data.schemaVersion !== SCHEMA_VERSION) throw invalid('the managed binding store', `has schema version ${data.schemaVersion}, not ${SCHEMA_VERSION}`);
+ if (data.schemaVersion !== SCHEMA_VERSION && data.schemaVersion !== SCHEMA_VERSION_ROWS) throw invalid('the managed binding store', `has schema version ${data.schemaVersion}, not ${SCHEMA_VERSION} or ${SCHEMA_VERSION_ROWS}`);
if (data.environmentFingerprint !== expect.environmentFingerprint || data.appUniqueName !== expect.appUniqueName || data.solutionUniqueName !== expect.solutionUniqueName) {
throw invalid('the managed binding store', 'belongs to another environment, app or solution');
}
@@ -1081,6 +1388,9 @@ function parseEnvelope(text, expect) {
const invalidGroups = new Map();
const identity = (x, where) => {
if (!isObj(x) || !FAMILIES.includes(x.family) || !nonempty(x.key)) throw invalid(where, 'has no family and key');
+ // A configuration family is a version-2 unit: a version-1 file holding one was not written by this store, and the
+ // whole file is refused rather than read with a protocol its version does not promise.
+ if (isRowFamily(x.family) && data.schemaVersion !== SCHEMA_VERSION_ROWS) throw invalid(where, `is a ${x.family} unit in a version ${data.schemaVersion} store`);
return groupId(x.family, x.key);
};
const markInvalid = (id, e) => { if (!invalidGroups.has(id)) invalidGroups.set(id, e.message); };
@@ -1089,6 +1399,7 @@ function parseEnvelope(text, expect) {
const id = identity(g, `groups[${i}]`);
if (groupIds.has(id)) throw invalid(`groups[${i}]`, 'repeats a group');
groupIds.add(id);
+ checkRowExtensions(g, 'group', `groups[${i}]`);
try { validateGroup(g, header, `groups[${i}]`); } catch (e) { markInvalid(id, e); }
});
const attemptIds = new Set();
@@ -1098,6 +1409,7 @@ function parseEnvelope(text, expect) {
// One attempt per group: a second would mean two different intents both waiting to be proved.
if (attemptIds.has(id)) throw invalid(`attempts[${i}]`, 'repeats an attempt for one group');
attemptIds.add(id);
+ checkRowExtensions(a, 'attempt', `attempts[${i}]`);
try {
validateAttempt(a, `attempts[${i}]`);
if (attemptTokens.has(a.token)) throw invalid(`attempts[${i}]`, 'repeats an attempt token');
@@ -1140,6 +1452,21 @@ function parseEnvelope(text, expect) {
};
data.groups.forEach((g, i) => claim(g, `groups[${i}]`));
data.attempts.forEach((a, i) => claim(a, `attempts[${i}]`));
+ // The child rows of the configuration families, by their own table: a value, parameter, property or condition row
+ // bound by two groups (or reserved by one group's attempt and bound by another) is refused for the whole file.
+ const rowOwner = new Map();
+ const claimRow = (x, kind, id, where) => {
+ if (!isRowFamily(x.family) || !ROW_TABLE[kind] || typeof id !== 'string') return;
+ const k = `${ROW_TABLE[kind]}\u0000${rowIdKey(id)}`;
+ const owner = rowOwner.get(k);
+ const gid = groupId(x.family, x.key);
+ if (owner && owner !== gid) throw invalid(where, `binds the ${ROW_TABLE[kind]} row ${id} that another group binds`);
+ rowOwner.set(k, gid);
+ };
+ data.groups.forEach((g, i) => { if (isObj(g) && Array.isArray(g.records)) g.records.forEach((r) => isObj(r) && claimRow(g, r.kind, r.id, `groups[${i}]`)); });
+ data.attempts.forEach((a, i) => {
+ if (isObj(a) && isObj(a.rowProtocol) && Array.isArray(a.rowProtocol.rows)) a.rowProtocol.rows.forEach((r) => isObj(r) && claimRow(a, r.kind, r.id, `attempts[${i}]`));
+ });
return { envelope: data, invalidGroups };
}
@@ -1274,6 +1601,46 @@ function discoverManagedStore(args) {
* `barrier` (lib/publication-barrier.js) receives the scope registrations, holds and quarantines the handle forwards.
* `deps`, for tests: `writeFileAtomic(path, text)` and `lease` (the record-lease.js deps).
*/
+// Charge one write's growth to SEVERAL attempts' reservations (a set mutation: mutate's `spend` named more than one).
+// Each participant first pays its own positive growth — the bytes of its attempt as this write leaves it against the
+// bytes it had on disk, its reservation left out so the charge does not chase itself. What the file grew by beyond
+// those (the envelope's own fields, indentation, the digits the charges add) is then given out in the order the
+// participants were named, each up to what is left of its reservation, and the text is settled again until the charges
+// stop changing. An attempt the change never named is never charged: its reservation is for its own completion.
+// A participant with no reservation (an attempt an older build prepared) pays nothing, as with one spender.
+// Answers the text to write.
+function chargeParticipants(next, was, tokens, prevBytes, text) {
+ const sized = (a) => {
+ if (!a) return 0;
+ const { completionReserve, ...rest } = a;
+ return Buffer.byteLength(JSON.stringify(rest, null, 2), 'utf8');
+ };
+ const parts = tokens.map((t) => next.attempts.find((a) => a.token === t)).filter((a) => a && a.completionReserve);
+ const start = parts.map((a) => a.completionReserve.used);
+ const self = parts.map((a, i) => {
+ const before = sized(was.attempts.find((x) => x.token === a.token));
+ return Math.min(a.completionReserve.bytes - start[i], Math.max(0, sized(a) - before));
+ });
+ const selfTotal = self.reduce((s, n) => s + n, 0);
+ let out = text;
+ for (let pass = 0; pass < 8; pass += 1) {
+ let residual = Math.max(0, Buffer.byteLength(out, 'utf8') - prevBytes - selfTotal);
+ let changed = false;
+ parts.forEach((a, i) => {
+ const base = start[i] + self[i];
+ const take = Math.min(a.completionReserve.bytes - base, residual);
+ residual -= take;
+ if (a.completionReserve.used !== base + take) {
+ a.completionReserve.used = base + take;
+ changed = true;
+ }
+ });
+ if (!changed) break;
+ out = `${JSON.stringify(next, null, 2)}\n`;
+ }
+ return out;
+}
+
function openManagedBindings({ workspaceDir, environment, appUniqueName, solutionUniqueName, barrier = null, deps = {} }) {
const ctx = resolveContext({ workspaceDir, environment, appUniqueName, solutionUniqueName });
const write = typeof deps.writeFileAtomic === 'function' ? deps.writeFileAtomic : writeFileAtomic;
@@ -1307,17 +1674,23 @@ function openManagedBindings({ workspaceDir, environment, appUniqueName, solutio
const lease = withRecordLease(root, ctx.file, () => {
const disk = readStoreFile({ ...ctx, root, full }) || { envelope: emptyEnvelope(ctx.expect), invalidGroups: new Map() };
const next = clone(disk.envelope);
- let spender = null;
+ // Every attempt the change spent for, in the order it first said so. A set mutation (markAttemptSetSending, a
+ // seal for several rows) names more than one, and each of them must pay for what it adds.
+ const spenders = [];
let admitNow = false;
- const answer = change(next, disk, (token) => { spender = token; }, () => { admitNow = true; });
+ const answer = change(next, disk, (token) => { if (!spenders.includes(token)) spenders.push(token); }, () => { admitNow = true; });
if (answer && typeof answer.then === 'function') throw storeError(CODES.notSettled, 'a managed binding change must be synchronous');
next.revision = disk.envelope.revision + 1;
+ // The first configuration-family unit upgrades the file to version 2 in this same write; a version-2 file stays 2,
+ // and a version-1 file written only for the original families stays 1, byte for byte what an older build writes.
+ const rowUnits = next.groups.some((g) => isRowFamily(g.family)) || next.attempts.some((a) => isRowFamily(a.family));
+ next.schemaVersion = disk.envelope.schemaVersion === SCHEMA_VERSION_ROWS || rowUnits ? SCHEMA_VERSION_ROWS : SCHEMA_VERSION;
const prevBytes = typeof disk.bytes === 'number' ? disk.bytes : 0;
let text = `${JSON.stringify(next, null, 2)}\n`;
// Charge the growth to the spending attempt's reservation. Recording the charge changes the text by a few digits,
// so it is settled again until the size is stable (two or three passes; the base reservation covers the digits).
- const own = spender ? findAttempt(next, spender) : null;
const admitting = admit === true || admitNow;
+ const own = spenders.length === 1 ? findAttempt(next, spenders[0]) : null;
if (own && own.completionReserve && !admitting) {
const start = own.completionReserve.used;
for (let pass = 0; pass < 4; pass += 1) {
@@ -1327,6 +1700,8 @@ function openManagedBindings({ workspaceDir, environment, appUniqueName, solutio
own.completionReserve.used = used;
text = `${JSON.stringify(next, null, 2)}\n`;
}
+ } else if (spenders.length > 1 && !admitting) {
+ text = chargeParticipants(next, disk.envelope, spenders, prevBytes, text);
}
// A file larger than any open reads back (readStoreFile: MAX_BYTES) would be written, then refused by every later
// run, the attempt it records with it: refuse the change instead, before the disk is touched. A write that does
@@ -1400,6 +1775,158 @@ function openManagedBindings({ workspaceDir, environment, appUniqueName, solutio
return owned.length;
};
+ // A sending attempt of a configuration family, at the window epoch the caller claimed (sealRowDispatch, markRowEffectDispatch).
+ const sendingRowAttempt = (env, disk, token, epoch) => {
+ const a = requireAttempt(env, disk, token);
+ if (!isRowFamily(a.family) || !a.rowProtocol) throw storeError(CODES.requestMismatch, 'the request names an attempt that keeps no row protocol');
+ if (a.phase !== 'sending' || !a.expected) throw storeError(CODES.requestMismatch, `the managed ${a.family} "${a.key}" attempt is not sending; nothing is sent under it`);
+ if (a.sendWindow && epoch !== undefined && epoch !== null && a.sendWindow.epoch !== epoch) throw storeError(CODES.pending, `the managed ${a.family} "${a.key}" attempt was claimed by another run since this send began; the request is not sent`);
+ return a;
+ };
+
+ // A commit proposal (commitGroup, commitGroupSet) is checked whole before anything else: a list that repeats a
+ // (kind, key) or an id must be refused, not folded into a map where the last record silently wins, and a proof must
+ // carry every field it promises.
+ function checkCommitProposal({ records, proof, adoptionApprovedChildren } = {}) {
+ try {
+ if (!Array.isArray(records)) throw invalid('the proposed records', 'is not a list');
+ const keys = new Set();
+ const ids = new Set();
+ records.forEach((rec, i) => {
+ const where = `the proposed records[${i}]`;
+ validateRecord(rec, ctx.expect, where);
+ const k = `${rec.kind}\u0000${rec.key}`;
+ if (keys.has(k)) throw invalid(where, `repeats ${rec.kind} "${rec.key}"`);
+ keys.add(k);
+ const id = rec.id.toLowerCase();
+ if (id !== NOTES_CONTROL && ids.has(id)) throw invalid(where, `repeats the id ${rec.id}`);
+ ids.add(id);
+ });
+ validateProof(proof, 'the proposed proof');
+ if (adoptionApprovedChildren !== undefined) {
+ if (!Array.isArray(adoptionApprovedChildren)) throw invalid('the approved child adoptions', 'is not a list');
+ adoptionApprovedChildren.forEach((c, i) => {
+ closedKeys(c, ['kind', 'key', 'id'], `the approved child adoptions[${i}]`);
+ if (!nonempty(c.kind) || !nonempty(c.key) || !nonempty(c.id)) throw invalid(`the approved child adoptions[${i}]`, 'is incomplete');
+ });
+ }
+ } catch (e) {
+ throw storeError(CODES.groupInvalid, `a managed group commit was refused before it was written: ${e.message}`);
+ }
+ }
+
+ // The commit of one attempt inside a lease-held change (see commitGroup): answers the committed group.
+ // For a configuration family (ROW_FAMILIES) every NEW record proves its own origin: a root `created` needs this
+ // attempt's acknowledged root create, a root `adopted` the root's exact `adoptionApproved`; a child `created` needs
+ // its OWN child-create receipt (an acknowledged root never stands in for it), a child `adopted` an exact
+ // { kind, key, id } entry of `adoptionApprovedChildren`. A parent's approval or acknowledgement never mints a child.
+ function commitInto(env, disk, { token, baseGeneration, records, proof, consumerState, publication = null, proofSchema, adoptionApproved = false, adoptionApprovedChildren = [] }) {
+ const a = requireAttempt(env, disk, token);
+ if (a.baseGeneration !== baseGeneration) throw storeError(CODES.conflict, 'the managed attempt is based on another generation');
+ if (!a.expected) throw storeError(CODES.notSettled, 'an attempt that was never sent has nothing to commit');
+ const rowFamily = isRowFamily(a.family);
+ const effects = env.workflowEffects.filter((e) => e.attemptToken === token);
+ // Every workflow effect this attempt owns retires in this same write, so none must still be open: an effect
+ // that may have reached the server must be proved first, and one never sent must be sent and proved, or found
+ // fulfilled by a read (fulfillEffect). The refusal leaves the attempt and its effects as they are, and no other
+ // attempt's effects are read or touched.
+ if (effects.some((e) => e.state !== 'confirmed' && e.state !== 'fulfilled')) throw storeError(CODES.pending, `the managed ${a.family} "${a.key}" has a workflow effect that is not confirmed`);
+ const old = env.groups.find((g) => g.family === a.family && g.key === a.key) || null;
+ // A publish of the old generation that may have been sent is settled first (a read-only confirmation, or it stays
+ // blocked). Carried over a new generation, a later read of the OLD layer would confirm the NEW group and drop
+ // the new generation's own debt; the new debt is never folded into the old dispatch either.
+ if (old && old.publication && UNCERTAIN.has(old.publication.state)) {
+ throw storeError(CODES.publicationUncertain, `the managed ${a.family} "${a.key}" has a publish that may have been sent and is not proved live; a new generation is committed only after it is confirmed`, blockedPublication(old.publication.scope, old.publication.dispatchToken));
+ }
+ const acknowledged = rootCreateAcknowledged(a);
+ const receipt = a.acknowledgedChildCreates || [];
+ // Strictly `true`: a truthy flag computed carelessly ('yes', 1) must not stand in for the maker's approval.
+ if (!old && !acknowledged && adoptionApproved !== true) {
+ throw storeError(CODES.adoptionRequired, `the managed ${a.family} "${a.key}" root was never acknowledged as created; binding it needs its adoption approval`);
+ }
+ // The create evidence of a dashboard root is the store's to mint and keep, never a caller's to propose: a record
+ // read back from the group and handed in again may carry it, but only exactly as the store keeps it on that root
+ // in this commit (checked below); it is set from the store's own, never from the caller's.
+ const echoedMarkers = [];
+ const proposed = (records || []).map((rec) => {
+ if (rec.localCreateDraft === undefined) return rec;
+ const { localCreateDraft, ...rest } = rec;
+ echoedMarkers.push({ kind: rec.kind, key: rec.key, marker: localCreateDraft });
+ return rest;
+ });
+ const merged = [];
+ const byKey = new Map();
+ for (const rec of proposed) byKey.set(`${rec.kind}\u0000${rec.key}`, rec);
+ for (const rec of old ? old.records : []) {
+ const k = `${rec.kind}\u0000${rec.key}`;
+ const next = byKey.get(k);
+ if (!next) { merged.push(rec); continue; }
+ if (String(next.id).toLowerCase() !== String(rec.id).toLowerCase()) {
+ throw storeError(CODES.completion, `the managed ${a.family} "${a.key}" would bind ${rec.kind} "${rec.key}" to another row than it holds`);
+ }
+ // A configuration record keeps the origin it was first bound with, whatever the proposal says.
+ merged.push({ ...next, origin: rowFamily || rec.origin === 'adopted' ? rec.origin : next.origin });
+ byKey.delete(k);
+ }
+ for (const rec of byKey.values()) {
+ // A new record claims `created` only on this attempt's acknowledged root create, or, for a child, on this
+ // attempt's child-create receipt naming that same (kind, key, id); a lost answer needs adoption. A receipt
+ // never covers the root.
+ const isRoot = rec.kind === a.root.kind && rec.key === a.root.key;
+ const receipted = !isRoot && rowIdKey(rec.id) !== rowIdKey(a.root.id)
+ && receipt.some((c) => c.kind === rec.kind && c.key === rec.key && rowIdKey(c.id) === rowIdKey(rec.id));
+ if (rec.origin === 'created' && !acknowledged && !receipted) throw storeError(CODES.completion, `the managed ${a.family} "${a.key}" cannot record ${rec.kind} "${rec.key}" as created without an acknowledged create`);
+ if (rowFamily) {
+ if (isRoot && rec.origin === 'adopted' && adoptionApproved !== true) throw storeError(CODES.adoptionRequired, `the managed ${a.family} "${a.key}" root is recorded adopted without its adoption approval`);
+ if (isRoot && rec.origin === 'created' && !acknowledged) throw storeError(CODES.completion, `the managed ${a.family} "${a.key}" root was never acknowledged as created`);
+ if (!isRoot && rec.origin === 'created' && !receipted) throw storeError(CODES.completion, `the managed ${a.family} "${a.key}" cannot record ${rec.kind} "${rec.key}" as created without its own child-create receipt`);
+ if (!isRoot && rec.origin === 'adopted' && !adoptionApprovedChildren.some((c) => c.kind === rec.kind && c.key === rec.key && rowIdKey(c.id) === rowIdKey(rec.id))) {
+ throw storeError(CODES.adoptionRequired, `the managed ${a.family} "${a.key}" ${rec.kind} "${rec.key}" is recorded adopted without its own adoption approval`);
+ }
+ }
+ // A child the group did not hold before is bound only when the expected proof, persisted before the send,
+ // named it under that id: an observation cannot add a binding the attempt never said it would make.
+ const planned = isRoot || a.expected.children.some((c) => c.kind === rec.kind && c.key === rec.key && String(c.id).toLowerCase() === String(rec.id).toLowerCase());
+ if (!planned) throw storeError(CODES.completion, `the managed ${a.family} "${a.key}" would bind ${rec.kind} "${rec.key}", which its expected proof does not name`);
+ merged.push(rec);
+ }
+ const rootRec = merged.find((r) => r.kind === a.root.kind && r.key === a.root.key);
+ if (!rootRec || String(rootRec.id).toLowerCase() !== a.root.id) throw storeError(CODES.completion, `the managed ${a.family} "${a.key}" root was not observed under its expected id`);
+ // The created dashboard root's create evidence: minted from this attempt's acknowledged receipt, or kept from
+ // the generation before for the same root. Never carried to another root, and gone with a retired group.
+ const oldRoot = old ? old.records.find((r) => r.kind === a.root.kind && r.key === a.root.key) : null;
+ let marker = null;
+ if (oldRoot && oldRoot.localCreateDraft && String(oldRoot.id).toLowerCase() === a.root.id) marker = clone(oldRoot.localCreateDraft);
+ else if (!old && dashboardCreateAcknowledged(a)) {
+ const d = a.dashboardCreate;
+ marker = { formatVersion: 1, rootId: a.root.id, attemptToken: a.token, draftSha256: d.draftSha256, bodySha256: d.bodySha256 };
+ }
+ const kept = marker && rootRec.origin === 'created' ? marker : null;
+ if (kept) merged[merged.indexOf(rootRec)] = { ...rootRec, localCreateDraft: kept };
+ for (const e of echoedMarkers) {
+ if (!(kept && e.kind === a.root.kind && e.key === a.root.key && canonicalJson(e.marker) === canonicalJson(kept))) {
+ throw storeError(CODES.groupInvalid, `a managed group commit was refused before it was written: the proposed ${e.kind} "${e.key}" carries create evidence only the store records`);
+ }
+ }
+ for (const child of a.expected.children) {
+ const got = merged.find((r) => r.kind === child.kind && r.key === child.key);
+ if (!got || String(got.id).toLowerCase() !== String(child.id).toLowerCase()) throw storeError(CODES.completion, `the managed ${a.family} "${a.key}" lacks the expected ${child.kind} "${child.key}"`);
+ }
+ // The original declaration is the attempt's own, recorded before it sent, and nothing the caller passes here can
+ // replace it; the feature's consumer state is kept exactly as proved. A generation whose attempt recorded none
+ // keeps none: an older generation's original never describes this one.
+ const committed = {
+ family: a.family, key: a.key, generation: newToken(), previousGeneration: old ? old.generation : null,
+ root: a.root, proofSchema: proofSchema || a.expected.proofSchema, records: merged, proof, consumerState,
+ ...(a.declaration !== undefined ? { originalDeclaration: clone(a.declaration) } : {}), publication,
+ };
+ env.groups = env.groups.filter((g) => g !== old);
+ env.groups.push(committed);
+ env.attempts = env.attempts.filter((x) => x !== a);
+ env.workflowEffects = env.workflowEffects.filter((e) => e.attemptToken !== token);
+ return committed;
+ }
+
const handle = {
get file() { return ctx.full; },
snapshot() { return snapshotOf(state); },
@@ -1728,14 +2255,35 @@ function openManagedBindings({ workspaceDir, environment, appUniqueName, solutio
* children `origin: 'created'`; it never acknowledges the root, never stands in for the
* root's adoption approval, never turns a child the group already holds into a creation,
* and grants no deletion.
+ * epoch optional: the send window epoch the caller's answer came under; another epoch (the
+ * attempt was claimed by another run since) is `managed-settlement-pending`, nothing written.
+ * A configuration attempt's ROOT RECEIPT alone — { proof: null, acknowledgedRoot: true, phase: 'sending', epoch } —
+ * is written the moment a checked save acknowledged the root create, before any read-back or membership request:
+ * it sets only the acknowledgement, and the attempt stays `sending` (no saved observation), so its remaining
+ * requests can still be sent under it. It needs the current epoch and a root the row protocol prepared as a create.
*/
- noteSaved(token, { proof, acknowledgedRoot = false, acknowledgedChildCreates = [], phase = 'saved' } = {}) {
- if (phase !== 'saved' && phase !== 'state-pending' && phase !== 'membership-pending') throw storeError(CODES.notSettled, `noteSaved cannot move an attempt to ${phase}`);
+ noteSaved(token, { proof, acknowledgedRoot = false, acknowledgedChildCreates = [], phase = 'saved', epoch } = {}) {
+ const rootReceipt = phase === 'sending';
+ if (rootReceipt && !(proof === null && acknowledgedRoot === true && Array.isArray(acknowledgedChildCreates) && acknowledgedChildCreates.length === 0 && epoch !== undefined)) {
+ throw storeError(CODES.notSettled, 'a receipt written while an attempt is still sending records its acknowledged root create alone, under its epoch');
+ }
+ if (!rootReceipt && phase !== 'saved' && phase !== 'state-pending' && phase !== 'membership-pending') throw storeError(CODES.notSettled, `noteSaved cannot move an attempt to ${phase}`);
if (!Array.isArray(acknowledgedChildCreates)) throw storeError(CODES.completion, 'a child-create receipt is a list of { kind, key, id }');
mutate((env, disk, spend) => {
const a = requireAttempt(env, disk, token);
spend(token);
if (!a.expected) throw storeError(CODES.notSettled, 'an attempt cannot be saved before it was sent');
+ if (epoch !== undefined && !(a.sendWindow && a.sendWindow.epoch === epoch)) {
+ throw storeError(CODES.pending, `the managed ${a.family} "${a.key}" attempt was claimed by another run since this send began; its answer is not recorded`);
+ }
+ if (rootReceipt) {
+ const root = a.rowProtocol ? a.rowProtocol.rows.find((r) => r.parentId === null && r.kind === a.root.kind && r.key === a.root.key) : null;
+ if (!isRowFamily(a.family) || a.phase !== 'sending' || !root || root.mode !== 'create' || rowIdKey(root.id) !== rowIdKey(a.root.id) || a.expected.baseObservation !== null) {
+ throw storeError(CODES.notSettled, `the managed ${a.family} "${a.key}" has no root this sending attempt prepared as a create; nothing acknowledges it`);
+ }
+ a.acknowledgedRoot = true;
+ return;
+ }
if (acknowledgedRoot === true && a.expected.baseObservation !== null) {
throw storeError(CODES.notSettled, `the managed ${a.family} "${a.key}" edited an existing root; an answer to an edit never acknowledges a create`);
}
@@ -1783,124 +2331,193 @@ function openManagedBindings({ workspaceDir, environment, appUniqueName, solutio
* inside — `consumerState`, which is kept exactly as passed; a group committed by an attempt that recorded none has
* no `originalDeclaration`.
*/
- commitGroup({ token, baseGeneration, records, proof, consumerState, publication = null, proofSchema, adoptionApproved = false }) {
- // The proposal is checked whole before anything else: a list that repeats a (kind, key) or an id must be refused,
- // not folded into a map where the last record silently wins, and a proof must carry every field it promises.
- try {
- if (!Array.isArray(records)) throw invalid('the proposed records', 'is not a list');
- const keys = new Set();
- const ids = new Set();
- records.forEach((rec, i) => {
- const where = `the proposed records[${i}]`;
- validateRecord(rec, ctx.expect, where);
- const k = `${rec.kind}\u0000${rec.key}`;
- if (keys.has(k)) throw invalid(where, `repeats ${rec.kind} "${rec.key}"`);
- keys.add(k);
- const id = rec.id.toLowerCase();
- if (id !== NOTES_CONTROL && ids.has(id)) throw invalid(where, `repeats the id ${rec.id}`);
- ids.add(id);
- });
- validateProof(proof, 'the proposed proof');
- } catch (e) {
- throw storeError(CODES.groupInvalid, `a managed group commit was refused before it was written: ${e.message}`);
- }
+ commitGroup(proposal) {
+ checkCommitProposal(proposal);
let committed;
+ mutate((env, disk) => { committed = commitInto(env, disk, proposal); });
+ return clone(committed);
+ },
+ /**
+ * Commit several configuration groups in ONE write (each proposal as commitGroup takes it, plus, for a row family,
+ * `adoptionApprovedChildren`): either every group of the set is committed and its attempt removed, or nothing is
+ * written. A partial set never exposes some new generations without the others.
+ */
+ commitGroupSet(proposals) {
+ if (!Array.isArray(proposals) || proposals.length === 0) throw storeError(CODES.notSettled, 'commitGroupSet needs a non-empty list of proposals');
+ proposals.forEach(checkCommitProposal);
+ if (new Set(proposals.map((p) => p.token)).size !== proposals.length) throw storeError(CODES.notSettled, 'commitGroupSet names one attempt twice');
+ const out = [];
+ mutate((env, disk) => { for (const p of proposals) out.push(commitInto(env, disk, p)); });
+ return clone(out);
+ },
+ /**
+ * Accept configuration attempts that were deliberately never sent — a plan of existing rows only, each read fresh
+ * and found exactly as planned — in ONE write: each proposal as commitGroupSet takes it, plus the `capture`
+ * (readOnlyCapture) taken before that fresh read. Under the lease every capture is checked again: the attempt, its
+ * group and its effects byte-for-byte as captured (same digest, generation and epoch), the expected proof of an
+ * existing-row plan (a base observation), and nothing of it dispatched (attemptProvenUnsent). Then each is committed
+ * exactly as commitGroupSet commits it, consuming its prepared proof. Nothing is acknowledged, no dispatch flag
+ * moves, and a record the group does not already hold is bound only as `adopted` under its own approval — never
+ * `created`. Any refusal writes nothing and leaves every attempt held.
+ */
+ commitReadOnlyGroupSet(proposals) {
+ if (!Array.isArray(proposals) || proposals.length === 0) throw storeError(CODES.notSettled, 'commitReadOnlyGroupSet needs a non-empty list of proposals');
+ proposals.forEach(checkCommitProposal);
+ if (new Set(proposals.map((p) => p.token)).size !== proposals.length) throw storeError(CODES.notSettled, 'commitReadOnlyGroupSet names one attempt twice');
+ const out = [];
mutate((env, disk) => {
- const a = requireAttempt(env, disk, token);
- if (a.baseGeneration !== baseGeneration) throw storeError(CODES.conflict, 'the managed attempt is based on another generation');
- if (!a.expected) throw storeError(CODES.notSettled, 'an attempt that was never sent has nothing to commit');
- const effects = env.workflowEffects.filter((e) => e.attemptToken === token);
- // Every workflow effect this attempt owns retires in this same write, so none must still be open: an effect
- // that may have reached the server must be proved first, and one never sent must be sent and proved, or found
- // fulfilled by a read (fulfillEffect). The refusal leaves the attempt and its effects as they are, and no other
- // attempt's effects are read or touched.
- if (effects.some((e) => e.state !== 'confirmed' && e.state !== 'fulfilled')) throw storeError(CODES.pending, `the managed ${a.family} "${a.key}" has a workflow effect that is not confirmed`);
- const old = env.groups.find((g) => g.family === a.family && g.key === a.key) || null;
- // A publish of the old generation that may have been sent is settled first (a read-only confirmation, or it stays
- // blocked). Carried over a new generation, a later read of the OLD layer would confirm the NEW group and drop
- // the new generation's own debt; the new debt is never folded into the old dispatch either.
- if (old && old.publication && UNCERTAIN.has(old.publication.state)) {
- throw storeError(CODES.publicationUncertain, `the managed ${a.family} "${a.key}" has a publish that may have been sent and is not proved live; a new generation is committed only after it is confirmed`, blockedPublication(old.publication.scope, old.publication.dispatchToken));
- }
- const acknowledged = rootCreateAcknowledged(a);
- const receipt = a.acknowledgedChildCreates || [];
- // Strictly `true`: a truthy flag computed carelessly ('yes', 1) must not stand in for the maker's approval.
- if (!old && !acknowledged && adoptionApproved !== true) {
- throw storeError(CODES.adoptionRequired, `the managed ${a.family} "${a.key}" root was never acknowledged as created; binding it needs its adoption approval`);
- }
- // The create evidence of a dashboard root is the store's to mint and keep, never a caller's to propose: a record
- // read back from the group and handed in again may carry it, but only exactly as the store keeps it on that root
- // in this commit (checked below); it is set from the store's own, never from the caller's.
- const echoedMarkers = [];
- const proposed = (records || []).map((rec) => {
- if (rec.localCreateDraft === undefined) return rec;
- const { localCreateDraft, ...rest } = rec;
- echoedMarkers.push({ kind: rec.kind, key: rec.key, marker: localCreateDraft });
- return rest;
- });
- const merged = [];
- const byKey = new Map();
- for (const rec of proposed) byKey.set(`${rec.kind}\u0000${rec.key}`, rec);
- for (const rec of old ? old.records : []) {
- const k = `${rec.kind}\u0000${rec.key}`;
- const next = byKey.get(k);
- if (!next) { merged.push(rec); continue; }
- if (String(next.id).toLowerCase() !== String(rec.id).toLowerCase()) {
- throw storeError(CODES.completion, `the managed ${a.family} "${a.key}" would bind ${rec.kind} "${rec.key}" to another row than it holds`);
+ for (const p of proposals) {
+ const now = readOnlyCapture(disk.envelope, p.token);
+ const was = p.capture || {};
+ if (!now || now.digest !== was.digest || now.generation !== was.generation || now.epoch !== was.epoch) {
+ throw storeError(CODES.conflict, 'a managed group changed since its read-only acceptance was captured; nothing was accepted');
}
- merged.push({ ...next, origin: rec.origin === 'adopted' ? 'adopted' : next.origin });
- byKey.delete(k);
- }
- for (const rec of byKey.values()) {
- // A new record claims `created` only on this attempt's acknowledged root create, or, for a child, on this
- // attempt's child-create receipt naming that same (kind, key, id); a lost answer needs adoption. A receipt
- // never covers the root.
- const isRoot = rec.kind === a.root.kind && rec.key === a.root.key;
- const receipted = !isRoot && rowIdKey(rec.id) !== rowIdKey(a.root.id)
- && receipt.some((c) => c.kind === rec.kind && c.key === rec.key && rowIdKey(c.id) === rowIdKey(rec.id));
- if (rec.origin === 'created' && !acknowledged && !receipted) throw storeError(CODES.completion, `the managed ${a.family} "${a.key}" cannot record ${rec.kind} "${rec.key}" as created without an acknowledged create`);
- // A child the group did not hold before is bound only when the expected proof, persisted before the send,
- // named it under that id: an observation cannot add a binding the attempt never said it would make.
- const planned = isRoot || a.expected.children.some((c) => c.kind === rec.kind && c.key === rec.key && String(c.id).toLowerCase() === String(rec.id).toLowerCase());
- if (!planned) throw storeError(CODES.completion, `the managed ${a.family} "${a.key}" would bind ${rec.kind} "${rec.key}", which its expected proof does not name`);
- merged.push(rec);
+ const a = requireAttempt(env, disk, p.token);
+ const name = `the managed ${a.family} "${a.key}"`;
+ if (!isRowFamily(a.family) || !a.expected || !isObj(a.expected.baseObservation) || a.rowProtocol.rows.some((r) => r.mode !== 'update')) {
+ throw storeError(CODES.notSettled, `${name} is not a plan of existing rows with a base observation; it cannot be accepted without a send`);
+ }
+ if (!attemptProvenUnsent(a, env.workflowEffects)) throw storeError(CODES.pending, `${name} attempt may have sent something; it is recovered from its original expectation, never accepted read-only`);
+ const old = env.groups.find((g) => g.family === a.family && g.key === a.key) || null;
+ for (const rec of p.records) {
+ const held = old && old.records.some((r) => r.kind === rec.kind && r.key === rec.key);
+ if (!held && rec.origin !== 'adopted') throw storeError(CODES.adoptionRequired, `${name} ${rec.kind} "${rec.key}" was never created by this attempt; accepted without a send it can only be adopted`);
+ }
+ out.push(commitInto(env, disk, p));
}
- const rootRec = merged.find((r) => r.kind === a.root.kind && r.key === a.root.key);
- if (!rootRec || String(rootRec.id).toLowerCase() !== a.root.id) throw storeError(CODES.completion, `the managed ${a.family} "${a.key}" root was not observed under its expected id`);
- // The created dashboard root's create evidence: minted from this attempt's acknowledged receipt, or kept from
- // the generation before for the same root. Never carried to another root, and gone with a retired group.
- const oldRoot = old ? old.records.find((r) => r.kind === a.root.kind && r.key === a.root.key) : null;
- let marker = null;
- if (oldRoot && oldRoot.localCreateDraft && String(oldRoot.id).toLowerCase() === a.root.id) marker = clone(oldRoot.localCreateDraft);
- else if (!old && dashboardCreateAcknowledged(a)) {
- const d = a.dashboardCreate;
- marker = { formatVersion: 1, rootId: a.root.id, attemptToken: a.token, draftSha256: d.draftSha256, bodySha256: d.bodySha256 };
+ });
+ return clone(out);
+ },
+ /**
+ * Prepare the attempts of several configuration groups (ROW_FAMILIES) in ONE write, before anything is sent. Each
+ * plan: { family, key, baseGeneration, revision?, root, declarationSha256, rowProtocol, completionBytes? }. Every
+ * check of prepareAttempt applies to each (a usable group, no pending attempt, the generation it was planned on);
+ * any refusal writes nothing. The first such write upgrades a version-1 store to version 2. Answers the tokens, in
+ * order. `cohort` is reserved for command bars, which this store version does not hold: it must be null.
+ */
+ prepareAttemptSet(plans, { cohort = null } = {}) {
+ if (!Array.isArray(plans) || plans.length === 0) throw storeError(CODES.notSettled, 'prepareAttemptSet needs a non-empty list of plans');
+ if (cohort !== null) throw storeError(CODES.notSettled, 'prepareAttemptSet takes no cohort for configuration groups');
+ const prepared = plans.map((p) => {
+ if (!isObj(p) || !isRowFamily(p.family) || !nonempty(p.key)) throw storeError(CODES.notSettled, 'prepareAttemptSet prepares configuration groups only');
+ checkCompletionBytes(p.completionBytes, 'prepareAttemptSet `completionBytes`');
+ return { plan: p, token: newToken(), reserve: { bytes: completionReserveFor(undefined, p.completionBytes, `the managed ${p.family} "${p.key}"`), used: 0 } };
+ });
+ if (new Set(plans.map((p) => groupId(p.family, p.key))).size !== plans.length) throw storeError(CODES.notSettled, 'prepareAttemptSet names one group twice');
+ mutate((env, disk) => {
+ for (const { plan, token, reserve } of prepared) {
+ const { family, key, baseGeneration = null, revision, root, declarationSha256, rowProtocol } = plan;
+ if (revision !== undefined && revision !== disk.envelope.revision) throw storeError(CODES.conflict, `the managed binding store changed since the plan was made (revision ${disk.envelope.revision}, plan ${revision})`);
+ const unit = usable(unitOf(disk, family, key));
+ if (unit.attempt) throw storeError(CODES.pending, `the managed ${family} "${key}" already has a pending attempt`);
+ if ((unit.group ? unit.group.generation : null) !== baseGeneration) throw storeError(CODES.conflict, `the managed ${family} "${key}" changed since the plan was made`);
+ env.attempts.push({
+ family, key, token, baseGeneration, phase: 'prepared', root, knownScopes: [], declarationSha256, expected: null,
+ acknowledgedRoot: false, savedObservation: null, publication: null, completionReserve: reserve, rowProtocol: clone(rowProtocol),
+ });
}
- const kept = marker && rootRec.origin === 'created' ? marker : null;
- if (kept) merged[merged.indexOf(rootRec)] = { ...rootRec, localCreateDraft: kept };
- for (const e of echoedMarkers) {
- if (!(kept && e.kind === a.root.kind && e.key === a.root.key && canonicalJson(e.marker) === canonicalJson(kept))) {
- throw storeError(CODES.groupInvalid, `a managed group commit was refused before it was written: the proposed ${e.kind} "${e.key}" carries create evidence only the store records`);
+ }, { admit: true });
+ return prepared.map((x) => x.token);
+ },
+ /**
+ * Mark several prepared configuration attempts sending in ONE write, each with its complete expected proof:
+ * entries [{ token, expected }]. `claim` as markSending: 'first' (each must still be prepared) or 'continue' (each
+ * must prove that nothing it sent was carried out — attemptProvenUnsent, which a dispatched row or effect of its
+ * row protocol defeats). `observed: true` arms each send window at zero. Answers [{ token, epoch }].
+ */
+ markAttemptSetSending(entries, { claim = 'first', observed = true } = {}) {
+ if (!Array.isArray(entries) || entries.length === 0) throw storeError(CODES.notSettled, 'markAttemptSetSending needs a non-empty list');
+ if (claim !== 'first' && claim !== 'continue') throw storeError(CODES.notSettled, `markAttemptSetSending cannot claim an attempt to "${claim}"`);
+ const out = [];
+ mutate((env, disk, spend) => {
+ for (const { token, expected } of entries) {
+ const a = requireAttempt(env, disk, token);
+ if (!isRowFamily(a.family)) throw storeError(CODES.notSettled, 'markAttemptSetSending marks configuration attempts only');
+ const name = `the managed ${a.family} "${a.key}"`;
+ if (a.expected !== null && canonicalJson(a.expected) !== canonicalJson(expected)) throw storeError(CODES.completion, 'a sent attempt keeps the expected proof it was sent with');
+ if (claim === 'first' && a.phase !== 'prepared') throw storeError(CODES.pending, `${name} attempt was marked sending by another run`);
+ if (claim === 'continue' && !(observed === true && attemptProvenUnsent(a, env.workflowEffects))) throw storeError(CODES.pending, `${name} attempt no longer shows that nothing it sent was carried out; it is not sent again`);
+ spend(token);
+ a.expected = expected;
+ if (a.phase === 'prepared') {
+ a.phase = 'sending';
+ if (observed === true) a.sendWindow = { possible: 0, notStarted: 0, epoch: 1 };
+ } else if (claim === 'continue' && a.sendWindow) {
+ a.sendWindow.epoch += 1;
}
+ out.push({ token, epoch: a.sendWindow ? a.sendWindow.epoch : null });
}
- for (const child of a.expected.children) {
- const got = merged.find((r) => r.kind === child.kind && r.key === child.key);
- if (!got || String(got.id).toLowerCase() !== String(child.id).toLowerCase()) throw storeError(CODES.completion, `the managed ${a.family} "${a.key}" lacks the expected ${child.kind} "${child.key}"`);
+ });
+ return out;
+ },
+ /**
+ * Seal what ONE request is about to carry for the rows of a sending configuration attempt, and mark them dispatched,
+ * in one write before the request leaves (lib/managed-create-transport.js). rows: [{ kind, key, id, sentFields,
+ * sentSha256 }] — every row the request contains (a deep insert seals its root and children together). A row the
+ * protocol does not name under that id, a row already dispatched (its first sealed request is kept), or an epoch
+ * that is not the window's current one is refused: nothing is written and the request is not sent.
+ */
+ sealRowDispatch({ token, epoch, rows } = {}) {
+ if (!Array.isArray(rows) || rows.length === 0) throw storeError(CODES.notSettled, 'sealRowDispatch needs the rows the request carries');
+ mutate((env, disk, spend) => {
+ const a = sendingRowAttempt(env, disk, token, epoch);
+ spend(token);
+ for (const s of rows) {
+ const r = a.rowProtocol.rows.find((x) => x.kind === s.kind && x.key === s.key);
+ if (!r || r.id !== normalizeGuid(s.id)) throw storeError(CODES.requestMismatch, `the request carries a ${s.kind} row the attempt of the managed ${a.family} "${a.key}" did not prepare under that id`);
+ if (r.dispatched) throw storeError(CODES.requestMismatch, `the ${s.kind} row ${r.id} of the managed ${a.family} "${a.key}" was already sent once; it is not sent again`);
+ r.sentFields = [...s.sentFields].sort();
+ r.sentSha256 = s.sentSha256;
+ r.dispatched = true;
}
- // The original declaration is the attempt's own, recorded before it sent, and nothing the caller passes here can
- // replace it; the feature's consumer state is kept exactly as proved. A generation whose attempt recorded none
- // keeps none: an older generation's original never describes this one.
- committed = {
- family: a.family, key: a.key, generation: newToken(), previousGeneration: old ? old.generation : null,
- root: a.root, proofSchema: proofSchema || a.expected.proofSchema, records: merged, proof, consumerState,
- ...(a.declaration !== undefined ? { originalDeclaration: clone(a.declaration) } : {}), publication,
- };
- env.groups = env.groups.filter((g) => g !== old);
- env.groups.push(committed);
- env.attempts = env.attempts.filter((x) => x !== a);
- env.workflowEffects = env.workflowEffects.filter((e) => e.attemptToken !== token);
+ if (a.sendWindow) a.sendWindow.possible += 1;
});
- return clone(committed);
+ },
+ /** Mark one completion effect (a solution membership, a rule's state) of a sending configuration attempt dispatched, before it leaves. */
+ markRowEffectDispatch({ token, epoch, kind, id } = {}) {
+ mutate((env, disk, spend) => {
+ const a = sendingRowAttempt(env, disk, token, epoch);
+ spend(token);
+ const e = a.rowProtocol.effects.find((x) => x.kind === kind && x.id === normalizeGuid(id));
+ if (!e) throw storeError(CODES.requestMismatch, `the ${kind} of ${id} is not an effect the attempt of the managed ${a.family} "${a.key}" prepared`);
+ if (e.dispatched) throw storeError(CODES.requestMismatch, `the ${kind} of ${id} was already sent once for the managed ${a.family} "${a.key}"; it is not sent again`);
+ e.dispatched = true;
+ if (a.sendWindow) a.sendWindow.possible += 1;
+ });
+ },
+ /**
+ * Claim ONE completion effect of a configuration attempt that its own record proves was never dispatched, after the
+ * rest of the attempt was sent: a duplicate rule's initial publication (`rule-state`), owed by a create whose root an
+ * answer acknowledged (noteSaved), when the run that saved it stopped before the publish left (a crash, a lost
+ * process). Checked against the record reread under the lease, never against what the caller read before:
+ * - the attempt keeps a row protocol, an expected proof and an observed send window, and its root create was
+ * acknowledged by its own answer;
+ * - its phase is `sending` or `state-pending` (its members are complete or still being added, never
+ * `membership-pending`), and the effect is the rule-state of its own root and still `dispatched: false`.
+ * Anything else is `managed-settlement-pending`, nothing written. The claim moves the window to a new epoch (an older
+ * run's dispatch under the old one is refused, as for 'continue') and puts the attempt back to `sending`, so the one
+ * publish goes through the same fenced transport as the original (markRowEffectDispatch seals it dispatched before
+ * it leaves, once): a publish that was, or may have been, dispatched is never claimed again. Answers { epoch }.
+ */
+ claimUnsentRowEffect({ token, kind, id } = {}) {
+ if (kind !== 'rule-state') throw storeError(CODES.notSettled, `claimUnsentRowEffect claims a rule's state only, not a ${kind}`);
+ let epoch = null;
+ mutate((env, disk, spend) => {
+ const a = requireAttempt(env, disk, token);
+ if (!isRowFamily(a.family) || !a.rowProtocol) throw storeError(CODES.notSettled, 'claimUnsentRowEffect claims configuration attempts only');
+ const name = `the managed ${a.family} "${a.key}"`;
+ if (!a.expected || !a.sendWindow || a.acknowledgedRoot !== true || (a.phase !== 'sending' && a.phase !== 'state-pending')) {
+ throw storeError(CODES.pending, `${name} attempt is not a saved create whose rule state alone is owed; nothing is sent under it`);
+ }
+ const e = a.rowProtocol.effects.find((x) => x.kind === kind && x.id === normalizeGuid(id));
+ if (!e || e.id !== rowIdKey(a.root.id)) throw storeError(CODES.requestMismatch, `the ${kind} of ${id} is not an effect the attempt of ${name} prepared for its root`);
+ if (e.dispatched) throw storeError(CODES.pending, `the ${kind} of ${id} was already sent once for ${name}; it is not sent again`);
+ spend(token);
+ a.sendWindow.epoch += 1;
+ a.phase = 'sending';
+ epoch = a.sendWindow.epoch;
+ });
+ return { epoch };
},
/**
* Mark, in one write immediately before the one send of `scope` under `token`:
@@ -2105,8 +2722,10 @@ function openManagedBindings({ workspaceDir, environment, appUniqueName, solutio
* based on `baseGeneration`, which must still be the group's generation. One write removes only that attempt and
* the effects it owns; the committed group, its publication debt and every other attempt and effect stay. Then,
* and only after the write, its own hold ends — a quarantine or an uncertain-send block is never cleared.
- * A `sending` attempt is never retired (it may have reached the service; runManagedFeature recovers or resumes it),
- * and a later read that finds nothing is not evidence that nothing started: `managed-settlement-pending`.
+ * A `sending` attempt is never retired here (it may have reached the service; runManagedFeature recovers or resumes it),
+ * and a later read that finds nothing is not evidence that nothing started: `managed-settlement-pending`. The one
+ * exception is retireProvenUnsentAttempt: a configuration attempt whose own record proves nothing was sent, released by
+ * the run that holds it, at its epoch.
* Answers { retired: true, effects } (the count of effect records removed with it).
*/
retireUnsentAttempt({ token, baseGeneration } = {}) {
@@ -2121,6 +2740,43 @@ function openManagedBindings({ workspaceDir, environment, appUniqueName, solutio
if (barrier) barrier.release(token);
return { retired: true, effects: removed };
},
+ /**
+ * Release the configuration attempt `token` that the run holding it at `epoch` just stopped before anything left: the
+ * SDK refused the operation before its first request (a Custom API label edit on an environment with more than one
+ * language, CUSTOM_API_LABELS_UNSUPPORTED), so the attempt is `sending` but its own record proves nothing it may have
+ * sent can land (attemptProvenUnsent: a send window that counted no possible send, no row or effect dispatched, no
+ * acknowledgement or saved observation). Kept, it would hold its group for a declaration that will never be sent:
+ * every later build — the earlier declaration, any other edit, even the same one — would stop on a pending attempt
+ * prepared for another declaration. Under the record lease the file is reread, and the attempt must keep a row
+ * protocol, still be at `epoch` (another run that claimed it since owns it), still prove nothing was sent, still be
+ * based on its group's generation, and own no workflow effect a read found made. One write removes only that attempt
+ * and the effects it owns; then its own hold ends. Anything else is refused with nothing written, and the attempt
+ * stays on its recovery path. A later read that finds nothing is never this proof: only the attempt's own record is.
+ * Answers { retired: true, effects }.
+ */
+ retireProvenUnsentAttempt({ token, epoch } = {}) {
+ if (typeof token !== 'string' || !token) throw storeError(CODES.notSettled, 'retireProvenUnsentAttempt needs the attempt token');
+ if (!Number.isInteger(epoch)) throw storeError(CODES.notSettled, 'retireProvenUnsentAttempt needs the send window epoch its run holds');
+ let removed = 0;
+ mutate((env, disk) => {
+ const a = requireAttempt(env, disk, token);
+ const name = `the managed ${a.family} "${a.key}"`;
+ if (!isRowFamily(a.family) || !a.rowProtocol) throw storeError(CODES.notSettled, `${name} attempt keeps no row protocol; it is not released here`);
+ if (!a.sendWindow || a.sendWindow.epoch !== epoch) throw storeError(CODES.pending, `${name} attempt was claimed by another run since this send began; it is not released`);
+ if (!attemptProvenUnsent(a, env.workflowEffects)) throw storeError(CODES.pending, `${name} attempt may have been sent; it is recovered, never released`);
+ const g = env.groups.find((x) => x.family === a.family && x.key === a.key);
+ if ((g ? g.generation : null) !== a.baseGeneration) throw storeError(CODES.conflict, `${name} changed since the attempt was prepared`);
+ const owned = env.workflowEffects.filter((e) => e.attemptToken === a.token);
+ // A fulfilled effect never left either, but it records that its target was reached: it settles only with a commit.
+ if (owned.some((e) => e.state !== 'definitely-unsent' || e.dispatchToken !== null)) throw storeError(CODES.pending, `${name} attempt has a change a read found already made; it is never released`);
+ env.attempts = env.attempts.filter((x) => x !== a);
+ env.workflowEffects = env.workflowEffects.filter((e) => e.attemptToken !== a.token);
+ removed = owned.length;
+ });
+ // As retireUnsentAttempt: only after the durable write does the attempt's own hold end.
+ if (barrier) barrier.release(token);
+ return { retired: true, effects: removed };
+ },
/**
* Step 1 of a retirement: observe the group (`family`, `key`) BEFORE the fresh service reads that prove its root
* absent. Rereads the file and answers { observation }: an opaque fingerprint of the group, its pending attempt and
@@ -2468,6 +3124,8 @@ function managedManifestView(snapshot) {
records: clone(g.records), proof: clone(g.proof),
declaration: g.consumerState && g.consumerState.declaration !== undefined ? clone(g.consumerState.declaration) : undefined,
originalDeclaration: g.originalDeclaration !== undefined ? clone(g.originalDeclaration) : undefined,
+ // A configuration group (ROW_FAMILIES) keeps no declaration: verify reads its rows' last confirmed baselines.
+ ...(isRowFamily(g.family) ? { rows: clone(g.consumerState.rows) } : {}),
});
}
return view;
@@ -2513,6 +3171,10 @@ module.exports = {
DECLARATION_MAX_BYTES,
CODES,
FAMILIES,
+ ROW_FAMILIES,
+ ROW_TABLE,
+ ROW_PROOF_SCHEMA,
+ SCHEMA_VERSION_ROWS,
ROOT_KIND,
storeFileName,
parseEnvelope,
@@ -2527,6 +3189,7 @@ module.exports = {
isStoreEnvironment,
REQUEST_SHAPES,
attemptProvenUnsent,
+ readOnlyCapture,
resumableCreate,
rootCreateAcknowledged,
dashboardCreateAcknowledged,
diff --git a/plugins/model-apps/scripts/lib/managed-create-batch.js b/plugins/model-apps/scripts/lib/managed-create-batch.js
new file mode 100644
index 000000000..ab505688e
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/managed-create-batch.js
@@ -0,0 +1,531 @@
+'use strict';
+// The one `$batch` a protected create set may send: a Custom API change set of an API the set already binds.
+//
+// The managed create gate (lib/managed-create-transport.js) refuses every `$batch` unsent unless the set opts in with
+// `batch: { apiBase, solution }` (runWithManagedCreateSet). With it, the gate asks this module to read the request, and
+// admits it only when it is EXACTLY the change set the SDK writes for a Custom API push that edits the bound API and adds
+// new children (cds-maker-sdk `renderChangeSet` over the Custom API operations, root PATCH -> new request parameters ->
+// new response properties). Anything else — another table, a GET or DELETE, a child PATCH, a create of a root, another
+// framing, a header or field the SDK does not write — is refused unsent. This module only parses and judges; the gate
+// classifies every constituent through the driver, seals them in ONE store write and reads the answer per constituent.
+//
+// The request, as the SDK writes it (CRLF; LF is read the same way when it is used throughout):
+// --batch_<uuid>
+// Content-Type: multipart/mixed;boundary=changeset_<uuid>
+// <blank>
+// --changeset_<uuid>
+// Content-Type: application/http
+// Content-Transfer-Encoding: binary
+// Content-ID: 1
+// <blank>
+// PATCH https://contoso.crm.dynamics.com/api/data/v9.0/customapis(<bound id>)?$select=customapiid HTTP/1.1
+// Content-Type: application/json;type=entry
+// MSCRM.SolutionUniqueName: <solution> only when the SDK context has a solution
+// If-Match: W/"14860046" the held version token; the root PATCH only
+// Prefer: return=representation
+// <blank>
+// {"isprivate":true}
+// --changeset_<uuid>
+// ... Content-ID: 2 ...
+// POST https://contoso.crm.dynamics.com/api/data/v9.0/customapirequestparameters?$select=customapirequestparameterid HTTP/1.1
+// ... (the same headers, no If-Match) ...
+// {"customapirequestparameterid":"<new id>","uniquename":"Extra",...,"[email protected]":"/customapis(<bound id>)"}
+// --changeset_<uuid>--
+// --batch_<uuid>--
+// <the one final line ending>
+// The answer, as the service sends it (note the space after ';' in the nested Content-Type):
+// --batchresponse_<uuid>
+// Content-Type: multipart/mixed; boundary=changesetresponse_<uuid>
+// <blank>
+// --changesetresponse_<uuid>
+// Content-Type: application/http
+// Content-Transfer-Encoding: binary
+// Content-ID: 1
+// <blank>
+// HTTP/1.1 200 OK
+// ETag: W/"14863812"
+// ... (other headers, which grant nothing) ...
+// <blank>
+// {"@odata.context":"<api base>/$metadata#customapis(customapiid)/$entity","@odata.etag":"W/\"14863812\"","customapiid":"<bound id>"}
+// --changesetresponse_<uuid>
+// ... Content-ID: 2 ... HTTP/1.1 201 Created ...
+// {"@odata.context":"<api base>/$metadata#customapirequestparameters(customapirequestparameterid)/$entity","@odata.etag":"W/\"…\"",
+// "customapirequestparameterid":"<new id>","_customapiid_value":"<bound id>"}
+// --changesetresponse_<uuid>--
+// --batchresponse_<uuid>--
+// A change set is atomic: when one operation fails, the service rolls every one back and answers the outer request with
+// that operation's status and a change set holding only the failed part (observed: outer 412, one part, Content-ID 2,
+// `HTTP/1.1 412 Precondition Failed`, an OData error envelope). Such an answer, like every answer that is not a complete
+// success, acknowledges nothing; nothing is ever re-sent from here.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/execute-batch-operations-using-web-api
+//
+// Neither the request nor the answer text is kept, logged or put in an error message: the errors name only part numbers
+// and fixed table names, and an answer is reduced to outcomes, statuses and a safe error code.
+
+const { canonicalJson, normalizeGuid } = require('./reconcile-common.js');
+
+// The gate's refusal code (managed-create-transport.js MISMATCH). It is spelled here, not imported, because the gate
+// loads this module.
+const MISMATCH = 'managed-create-request-mismatch';
+// The SDK's own bound on one change set (cds-maker-sdk MAX_BATCH_PARTS) — and the gate passes a smaller one, the rows the
+// set prepared, so no answer or request is read past what could belong to the set.
+const MAX_BATCH_PARTS = 1000;
+const UUID = '[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}';
+const GUID = new RegExp(`^${UUID}$`);
+// A held version token as the service issues it (`W/"<row version>"`); `*` or any other form is never a held token.
+const HELD_ETAG = /^W\/"\d+"$/;
+// One header line: an RFC 9110 token name, a colon, optional spaces and a value that neither starts nor ends with a
+// space. A folded continuation line starts with a space and does not match; tabs and other controls are refused for the
+// whole text before any line is read.
+const HEADER_LINE = /^([A-Za-z0-9!#$%&'*+.^_`|~-]+):[ ]*([^ ](?:.*[^ ])?)$/;
+const CONTROLS = /[\u0000-\u0009\u000b\u000c\u000e-\u001f\u007f]/;
+const MAX_HEADERS = 64;
+
+const BIND = '[email protected]';
+/** The three constituents a Custom API change set may carry: the bound root's PATCH and the two kinds of new child. */
+const ROLES = Object.freeze({
+ root: Object.freeze({ kind: 'customApi', table: 'customapis', key: 'customapiid', method: 'PATCH', status: 200, rank: 0 }),
+ requestParameter: Object.freeze({ kind: 'customApiRequestParameter', table: 'customapirequestparameters', key: 'customapirequestparameterid', method: 'POST', status: 201, rank: 1 }),
+ responseProperty: Object.freeze({ kind: 'customApiResponseProperty', table: 'customapiresponseproperties', key: 'customapiresponsepropertyid', method: 'POST', status: 201, rank: 2 }),
+});
+// The root fields the SDK may PATCH (cds-maker-sdk's Custom API diff: everything else of a root is immutable or a label
+// the SDK refuses to write).
+const ROOT_FIELDS = new Set(['name', 'displayname', 'description', 'isprivate', 'executeprivilegename']);
+// A new child's body, field for field as the SDK builds it: its caller-chosen primary key, the normalized declaration
+// and the bind to its API.
+const childFields = (role) => [ROLES[role].key, 'uniquename', 'name', 'displayname', 'description', 'type', 'logicalentityname', ...(role === 'requestParameter' ? ['isoptional'] : []), BIND];
+
+const isPlain = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
+const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
+
+function mismatch(message) {
+ return Object.assign(new Error(message), { code: MISMATCH });
+}
+
+// A framing fault while reading; the request side turns it into a refusal, the answer side into `unknown`.
+class Malformed extends Error {}
+const malformed = (why) => new Malformed(why);
+
+/**
+ * The batch option of a create set: { apiBase, solution }. `apiBase` is the SDK's configured API root — the origin and
+ * `/api/data/v<major>.<minor>` exactly as the SDK prefixes every URL (the bundle uses v9.0) — and `solution` the unique
+ * name the SDK context sends as MSCRM.SolutionUniqueName, or null when it sends none. Both are required: a constituent
+ * must carry exactly the solution header the prepared SDK context emits, never one added or stripped.
+ */
+function batchConfig(cfg) {
+ if (!isPlain(cfg)) throw new TypeError('the batch option of a create set is { apiBase, solution }');
+ let u;
+ try {
+ u = new URL(String(cfg.apiBase));
+ } catch {
+ throw new TypeError('the batch option names no API base URL');
+ }
+ if (u.protocol !== 'https:' || u.username || u.password || u.search || u.hash || !/^\/api\/data\/v\d+\.\d+$/.test(u.pathname) || cfg.apiBase !== `${u.origin}${u.pathname}`) {
+ throw new TypeError('the batch option\'s API base is https://<host>/api/data/v<major>.<minor>, with nothing else');
+ }
+ if (!own(cfg, 'solution') || !(cfg.solution === null || (typeof cfg.solution === 'string' && /^[A-Za-z0-9_]{1,128}$/.test(cfg.solution)))) {
+ throw new TypeError('the batch option names the solution its SDK context sends (a unique name), or null for none');
+ }
+ return Object.freeze({ apiBase: cfg.apiBase, solution: cfg.solution });
+}
+
+// The lines of a multipart text, with one line ending used throughout: CRLF, or LF when no CR appears at all. A bare CR,
+// a mix of the two or any other control character refuses the whole text. The one final line ending is dropped; any
+// more is an epilogue the walk below refuses.
+function linesOf(text) {
+ if (typeof text !== 'string' || CONTROLS.test(text)) return null;
+ const crlf = text.includes('\r');
+ if (crlf && /\r(?!\n)|(?<!\r)\n/.test(text)) return null;
+ const lines = text.split(crlf ? '\r\n' : '\n');
+ if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop();
+ return lines;
+}
+
+// `multipart/mixed;boundary=X`, with ordinary spaces around ';' and '=' (as the client's own multipart reader allows)
+// and X quoted or not; any other type, a second parameter, an escape or an empty boundary answers null.
+function multipartBoundary(value) {
+ const m = /^multipart\/mixed[ ]*;[ ]*boundary[ ]*=[ ]*("?)([A-Za-z0-9_-]+)\1[ ]*$/i.exec(String(value));
+ return m ? m[2] : null;
+}
+
+// One header block, up to and including its blank line: names are compared case-insensitively and may appear once.
+function headerBlock(lines, i, collides) {
+ const list = [];
+ const map = new Map();
+ for (; i < lines.length; i++) {
+ const line = lines[i];
+ if (line === '') return { list, map, next: i + 1 };
+ const m = HEADER_LINE.exec(line);
+ if (!m || collides(line)) throw malformed('a header line is not one well-formed header');
+ const lower = m[1].toLowerCase();
+ if (map.has(lower)) throw malformed('a header appears twice');
+ if (list.length >= MAX_HEADERS) throw malformed('too many headers');
+ map.set(lower, m[2]);
+ list.push({ name: m[1], value: m[2] });
+ }
+ throw malformed('a header block has no end');
+}
+
+/**
+ * Walk one batch holding exactly one change set: `--<outer>_<uuid>`, its one Content-Type header naming the
+ * `<inner>_<uuid>` boundary, the change set's parts, `--<inner>_<uuid>--`, `--<outer>_<uuid>--` and nothing after it.
+ * Each part is its three MIME headers, one start line, an HTTP header block and the body lines up to the next delimiter
+ * line. A delimiter is matched only as a whole line; a boundary anywhere else in the text is a collision and refuses it.
+ * Answers { boundary, parts: [{ contentId, start, headers, bodyLines }] } or throws Malformed.
+ */
+function walk(text, { outer, inner, limit, ordered }) {
+ const lines = linesOf(text);
+ if (!lines) throw malformed('its line endings are not one kind throughout, or it holds a control character');
+ const open = new RegExp(`^--(${outer}_${UUID})$`).exec(lines[0] || '');
+ if (!open) throw malformed('it does not open with its batch boundary');
+ const B = open[1];
+ const top = headerBlock(lines, 1, (line) => line.includes(`--${B}`));
+ const C = top.list.length === 1 && top.map.has('content-type') ? multipartBoundary(top.map.get('content-type')) : null;
+ if (!C || !new RegExp(`^${inner}_${UUID}$`).test(C)) throw malformed('its one part is not exactly one change set');
+ const delim = `--${C}`;
+ const close = `--${C}--`;
+ const collides = (line) => line.includes(delim) || line.includes(`--${B}`);
+ let i = top.next;
+ if (lines[i] !== delim) throw malformed('the change set does not open with its boundary');
+ i += 1;
+ const parts = [];
+ for (;;) {
+ if (parts.length >= limit) throw malformed('it holds more parts than the set prepared');
+ const mime = headerBlock(lines, i, collides);
+ const id = mime.map.get('content-id');
+ if (mime.list.length !== 3 || String(mime.map.get('content-type')).toLowerCase() !== 'application/http'
+ || String(mime.map.get('content-transfer-encoding')).toLowerCase() !== 'binary' || !/^[1-9][0-9]{0,3}$/.test(String(id))) {
+ throw malformed('a part does not have exactly the MIME headers of one HTTP operation');
+ }
+ const contentId = Number(id);
+ if (ordered && contentId !== parts.length + 1) throw malformed('its Content-IDs are not 1..N in order');
+ i = mime.next;
+ const start = lines[i];
+ if (start === undefined || start === '' || collides(start)) throw malformed('a part has no start line');
+ const http = headerBlock(lines, i + 1, collides);
+ i = http.next;
+ const bodyLines = [];
+ while (i < lines.length && lines[i] !== delim && lines[i] !== close) {
+ if (collides(lines[i])) throw malformed('a body holds a boundary');
+ bodyLines.push(lines[i]);
+ i += 1;
+ }
+ if (i >= lines.length) throw malformed('the change set has no end');
+ parts.push({ contentId, start, headers: http, bodyLines });
+ i += 1;
+ if (lines[i - 1] === close) break;
+ }
+ if (lines[i] !== `--${B}--` || i + 1 !== lines.length) throw malformed('the batch does not end right after its one change set');
+ return { boundary: B, parts };
+}
+
+// A JSON scanner for one flat object: `{ "key": scalar, ... }` with unique keys and string, number, boolean or null
+// values. JSON.parse alone keeps the last of two equal keys, which would let a request or an answer say two things at
+// once, and would accept nested values the shapes below never carry. Answers the object (own properties only, a key
+// such as "__proto__" included as data) or null.
+const JSON_WS = /[ \t\n\r]*/y;
+const JSON_STRING = /"(?:[^"\\\u0000-\u001f]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"/y;
+const JSON_SCALAR = /"(?:[^"\\\u0000-\u001f]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?|true|false|null/y;
+function flatJson(text) {
+ if (typeof text !== 'string') return null;
+ let at = 0;
+ const take = (re) => {
+ re.lastIndex = at;
+ const m = re.exec(text);
+ if (!m) return null;
+ at = re.lastIndex;
+ return m[0];
+ };
+ const ch = (c) => {
+ take(JSON_WS);
+ if (text[at] !== c) return false;
+ at += 1;
+ return true;
+ };
+ const out = {};
+ if (!ch('{')) return null;
+ take(JSON_WS);
+ if (!ch('}')) {
+ for (;;) {
+ take(JSON_WS);
+ const k = take(JSON_STRING);
+ if (k === null || !ch(':')) return null;
+ take(JSON_WS);
+ const v = take(JSON_SCALAR);
+ if (v === null) return null;
+ const key = JSON.parse(k);
+ if (own(out, key)) return null;
+ Object.defineProperty(out, key, { value: JSON.parse(v), enumerable: true, writable: true, configurable: true });
+ if (ch(',')) continue;
+ if (ch('}')) break;
+ return null;
+ }
+ }
+ take(JSON_WS);
+ return at === text.length ? out : null;
+}
+
+const stringOrNull = (v) => v === null || typeof v === 'string';
+
+// The body of one constituent, judged against the fields the SDK writes for its role. Answers a reason, or null.
+function bodyFault(role, json, boundId) {
+ if (role === 'root') {
+ const keys = Object.keys(json);
+ if (keys.length === 0 || !keys.every((k) => ROOT_FIELDS.has(k))) return 'patches nothing, or a field of the API the SDK never edits';
+ for (const k of keys) if (k === 'isprivate' ? typeof json[k] !== 'boolean' : !stringOrNull(json[k])) return `carries a ${k} that is not of its type`;
+ return null;
+ }
+ const want = childFields(role);
+ const keys = Object.keys(json);
+ if (keys.length !== want.length || !want.every((k) => own(json, k))) return 'does not carry exactly the fields of a new child';
+ const pk = ROLES[role].key;
+ if (typeof json[pk] !== 'string' || !GUID.test(json[pk])) return 'names no caller id for the new child';
+ if (typeof json.uniquename !== 'string' || json.uniquename === '') return 'names no unique name';
+ for (const k of ['name', 'displayname', 'description', 'logicalentityname']) if (!stringOrNull(json[k])) return `carries a ${k} that is not of its type`;
+ if (!Number.isSafeInteger(json.type) || json.type < 0) return 'carries a type that is not a type code';
+ if (role === 'requestParameter' && typeof json.isoptional !== 'boolean') return 'carries an isoptional that is not a boolean';
+ const bind = /^\/customapis\(([^()]*)\)$/.exec(typeof json[BIND] === 'string' ? json[BIND] : '');
+ if (!bind || !GUID.test(bind[1]) || normalizeGuid(bind[1]) !== boundId) return 'is not bound to the API the change set edits';
+ return null;
+}
+
+/**
+ * Read one `$batch` request { url, body, headers } (what the gate is asked with) as the Custom API change set the SDK
+ * writes, against `config` (batchConfig) and `limit` (the most parts the set can account for). Throws
+ * managed-create-request-mismatch for anything else. Answers {
+ * boundId, the one API every constituent targets (the root PATCH's id, every child's bind);
+ * constituents: [{ contentId, role: 'root' | 'requestParameter' | 'responseProperty', method, url, headers, body,
+ * json, id, ifMatch? }]
+ * } in request order: `headers` the constituent's HTTP headers as written, `body` its JSON text, `json` that object,
+ * `id` the row it writes (the root's URL id, a child's caller id) and `ifMatch` the root PATCH's version token.
+ */
+function parseCustomApiChangeset({ url, body, headers } = {}, config, { limit = MAX_BATCH_PARTS } = {}) {
+ const fail = (why) => { throw mismatch(`a $batch was not sent: ${why}`); };
+ if (url !== `${config.apiBase}/$batch`) fail('it is not posted to the configured API $batch endpoint');
+ // The SDK sends one request header of its own on a batch, the multipart Content-Type; it must name the body's boundary.
+ const outer = Object.entries(isPlain(headers) ? headers : {});
+ if (outer.length !== 1 || outer[0][0].toLowerCase() !== 'content-type') fail('its request headers are not exactly its multipart Content-Type');
+ const outerBoundary = multipartBoundary(outer[0][1]);
+ let framed;
+ try {
+ framed = walk(body, { outer: 'batch', inner: 'changeset', limit: Math.min(limit, MAX_BATCH_PARTS), ordered: true });
+ } catch (e) {
+ if (e instanceof Malformed) fail(`its framing is not one change set as the SDK writes it (${e.message})`);
+ throw e;
+ }
+ if (outerBoundary !== framed.boundary) fail('its Content-Type names another boundary than its body');
+ let boundId = null;
+ let rank = -1;
+ const constituents = framed.parts.map((p) => {
+ const what = `its part ${p.contentId}`;
+ const line = /^([A-Z]+) (\S+) HTTP\/1\.1$/.exec(p.start);
+ if (!line) fail(`${what} is not one HTTP/1.1 request`);
+ const [, method, partUrl] = line;
+ const prefix = `${config.apiBase}/`;
+ const rest = partUrl.startsWith(prefix) ? partUrl.slice(prefix.length) : null;
+ let role = null;
+ let id = null;
+ const root = rest === null ? null : /^customapis\(([^()]*)\)\?\$select=customapiid$/.exec(rest);
+ if (method === 'PATCH' && root && GUID.test(root[1])) {
+ role = 'root';
+ id = normalizeGuid(root[1]);
+ } else if (method === 'POST' && rest === 'customapirequestparameters?$select=customapirequestparameterid') {
+ role = 'requestParameter';
+ } else if (method === 'POST' && rest === 'customapiresponseproperties?$select=customapiresponsepropertyid') {
+ role = 'responseProperty';
+ }
+ if (!role) fail(`${what} is not the bound API's PATCH or a new request parameter or response property under the configured API base`);
+ if (ROLES[role].rank < rank || (role === 'root' && p.contentId !== 1)) fail(`${what} is out of the SDK's order (the API, then request parameters, then response properties)`);
+ rank = ROLES[role].rank;
+ const h = p.headers.map;
+ const allowed = ['content-type', 'prefer', ...(config.solution !== null ? ['mscrm.solutionuniquename'] : []), ...(role === 'root' ? ['if-match'] : [])];
+ if (h.size !== allowed.length || !allowed.every((k) => h.has(k))) fail(`${what} does not carry exactly the headers the SDK writes for it`);
+ if (h.get('content-type') !== 'application/json;type=entry' || h.get('prefer') !== 'return=representation') fail(`${what} does not ask for a JSON entry and its representation`);
+ if (config.solution !== null && h.get('mscrm.solutionuniquename') !== config.solution) fail(`${what} names another solution than the set's`);
+ const ifMatch = role === 'root' ? h.get('if-match') : undefined;
+ if (role === 'root' && !HELD_ETAG.test(ifMatch)) fail(`${what} is not conditional on a held version of the API`);
+ const json = p.bodyLines.length === 1 ? flatJson(p.bodyLines[0]) : null;
+ if (!json) fail(`${what} is not one flat JSON object with unique keys`);
+ if (role !== 'root') id = normalizeGuid(json[ROLES[role].key]);
+ const target = role === 'root' ? id : (/^\/customapis\(([^()]*)\)$/.exec(typeof json[BIND] === 'string' ? json[BIND] : '') || [])[1];
+ if (boundId === null && target && GUID.test(target)) boundId = normalizeGuid(target);
+ const fault = bodyFault(role, json, boundId);
+ if (fault) fail(`${what} ${fault}`);
+ return {
+ contentId: p.contentId, role, method, url: partUrl, headers: Object.fromEntries(p.headers.list.map((x) => [x.name, x.value])),
+ body: p.bodyLines[0], json, id, ...(role === 'root' ? { ifMatch } : {}),
+ };
+ });
+ const children = constituents.filter((k) => k.role !== 'root').length;
+ if (children === 0 || (children === constituents.length && children < 2)) {
+ fail('it is not an edit of the API with new children, nor two or more new children (one change goes on its own)');
+ }
+ return { boundId, constituents };
+}
+
+/**
+ * Why a driver's descriptor of one constituent does not describe it (null when it does). A constituent's descriptor
+ * is the gate's `rows` descriptor for exactly one row of the constituent's own table, plus what this boundary checks
+ * the constituent against: { type: 'rows', token, expectTable, expectKey, rows: [{ kind, key, id, parentId, sentFields,
+ * sentSha256 }], prepared, ifMatch? } — `prepared` the exact JSON object the driver prepared for it (compared with what
+ * the request carries, key for key and value for value), and `ifMatch` the version token the driver holds for the bound
+ * API (the root PATCH only).
+ */
+function constituentFault(c, k, boundId) {
+ const role = ROLES[k.role];
+ if (!isPlain(c) || c.type !== 'rows') return 'is not a change the set prepared';
+ if (!Array.isArray(c.rows) || c.rows.length !== 1 || c.expectId !== undefined || c.expectTable !== role.table || c.expectKey !== role.key) {
+ return `is not described as one row of ${role.table}`;
+ }
+ const r = c.rows[0];
+ if (!isPlain(r) || r.kind !== role.kind || r.answer !== undefined || normalizeGuid(r.id) !== k.id) return 'is described as another row than the one it writes';
+ const parent = r.parentId === null || r.parentId === undefined ? null : normalizeGuid(r.parentId);
+ if (parent !== (k.role === 'root' ? null : boundId)) return 'is described under another parent than the API it is bound to';
+ if (!isPlain(c.prepared) || canonicalJson(c.prepared) !== canonicalJson(k.json)) return 'does not carry exactly the change prepared for it';
+ if (k.role === 'root' ? !(typeof c.ifMatch === 'string' && HELD_ETAG.test(c.ifMatch) && c.ifMatch === k.ifMatch) : c.ifMatch !== undefined) {
+ return 'is not conditional on the version the set holds';
+ }
+ if (!Array.isArray(r.sentFields) || !r.sentFields.every((f) => typeof f === 'string' && own(k.json, f))) return 'seals a field it does not carry';
+ return null;
+}
+
+const statusOf = (res) => (res && Number.isInteger(res.statusCode) ? res.statusCode : res && Number.isInteger(res.status) ? res.status : null);
+
+// One header of an answer, read under any spelling of its name: undefined when absent, null when given more than once.
+function oneHeader(headers, name) {
+ const values = [];
+ for (const [k, v] of Object.entries(isPlain(headers) ? headers : {})) {
+ if (k.toLowerCase() !== name || v === null || v === undefined) continue;
+ for (const one of Array.isArray(v) ? v : [v]) values.push(String(one));
+ }
+ return values.length === 0 ? undefined : values.length === 1 ? values[0] : null;
+}
+
+// `<api base>/$metadata#<entity set>(<selected columns>)/$entity` -> { table, select } or null. The base is the
+// service's own spelling of the configured API base, compared case-insensitively.
+function contextOf(value, apiBase) {
+ if (typeof value !== 'string') return null;
+ const m = /^(.*)\/\$metadata#([A-Za-z_][A-Za-z0-9_]*)(?:\(([^()]*)\))?\/\$entity$/.exec(value);
+ if (!m || m[1].toLowerCase() !== apiBase.toLowerCase()) return null;
+ return { table: m[2].toLowerCase(), select: m[3] === undefined ? null : m[3] };
+}
+
+/**
+ * What one answered part says about its constituent, by the gate's identity rules applied to the part as an answer of
+ * its own (answerOf: every identity header and the body's primary key must name the constituent's row) and by what the
+ * captured success carries: the role's status (the API's PATCH 200, a new child 201), the body's OWN selected primary key
+ * naming the row (headers only supplement it), a well-formed `@odata.etag`, an `@odata.context` naming the constituent's
+ * own table with exactly its primary key selected, the root's ETag header (when present) equal to its body token,
+ * and each child's `_customapiid_value` naming the bound API. Anything naming another row, table or API is a conflict;
+ * anything missing, malformed or unexpected is unknown.
+ */
+function judgePart(part, k, admitted, answerOf) {
+ const role = ROLES[k.role];
+ const headers = Object.fromEntries(part.headers.list.map((x) => [x.name, x.value]));
+ const body = part.bodyLines.join('\n');
+ const ident = answerOf({ statusCode: part.status, headers, body }, { id: k.id, table: role.table, key: role.key });
+ let conflict = ident.outcome === 'conflict';
+ let unknown = ident.outcome === 'unknown' || part.status !== role.status || part.bodyLines.length !== 1;
+ const json = flatJson(part.bodyLines.length === 1 ? part.bodyLines[0] : null);
+ if (!json) {
+ unknown = true;
+ } else {
+ // The `$select` of the primary key makes the service echo it in the body: the body's own key is the evidence of
+ // which row the part wrote. An identity header (Location, OData-EntityId) may agree with it, never stand in for it,
+ // so a body without its key — or a context that did not select it — is unknown however well the headers read.
+ const pk = own(json, role.key) ? json[role.key] : undefined;
+ if (typeof pk !== 'string' || !GUID.test(pk)) unknown = true;
+ else if (normalizeGuid(pk) !== k.id) conflict = true;
+ const ctx = contextOf(json['@odata.context'], admitted.apiBase);
+ if (!ctx) unknown = true;
+ else if (ctx.table !== role.table) conflict = true;
+ else if (ctx.select !== role.key) unknown = true;
+ const etag = json['@odata.etag'];
+ if (typeof etag !== 'string' || !HELD_ETAG.test(etag)) unknown = true;
+ if (k.role === 'root') {
+ const header = oneHeader(headers, 'etag');
+ if (header !== undefined && header !== etag) unknown = true;
+ } else {
+ const parent = typeof json._customapiid_value === 'string' ? normalizeGuid(json._customapiid_value) : '';
+ if (!parent) unknown = true;
+ else if (parent !== admitted.boundId) conflict = true;
+ }
+ }
+ const extra = ident.answeredId ? { answeredId: ident.answeredId } : {};
+ if (conflict) return { outcome: 'conflict', status: part.status, ...extra };
+ if (unknown) return { outcome: 'unknown', status: part.status, ...extra };
+ return { outcome: 'acknowledged', status: part.status, ...extra };
+}
+
+/**
+ * Read the answer to an admitted change set, per constituent. `admitted` = { apiBase, boundId, constituents:
+ * [{ contentId, role, id }] } (parseCustomApiChangeset's, with the configured base). Answers {
+ * batchStatus, the outer status, or null;
+ * parts, one { outcome, status, answeredId? } per constituent, in request order: `status` is its own part's
+ * status, or null when no part answered it;
+ * failure? { contentId, status, code? }: the service reported this one constituent failed and the change set
+ * rolled back (the shape captured above); `code` only when it is a platform code such as 0x80040333.
+ * A diagnostic, never evidence of what exists.
+ * }
+ * Every constituent is acknowledged only when the whole change set is: outer 200, complete framing, one part for every
+ * Content-ID and none else, and every part acknowledged. A part naming another row is a conflict and stays one; every
+ * other constituent is then unknown, as is every constituent of a failed, partial, malformed or lost answer.
+ */
+function readChangesetAnswer(res, admitted) {
+ // Loaded here, not at the top: the gate loads this module, and answerOf is the gate's (one identity rule for a
+ // request on its own and for a constituent).
+ const { answerOf } = require('./managed-create-transport.js');
+ const batchStatus = statusOf(res);
+ const n = admitted.constituents.length;
+ const every = (outcome) => ({ batchStatus, parts: admitted.constituents.map(() => ({ outcome, status: null })) });
+ if (!res || res.error || batchStatus === null) return every('unknown');
+ const raw = Buffer.isBuffer(res.body) ? res.body.toString('utf8') : res.body;
+ let framed;
+ try {
+ framed = walk(raw, { outer: 'batchresponse', inner: 'changesetresponse', limit: n, ordered: false });
+ } catch (e) {
+ if (e instanceof Malformed) return every('unknown');
+ throw e;
+ }
+ const contentType = oneHeader(res.headers, 'content-type');
+ if (contentType !== undefined && multipartBoundary(contentType) !== framed.boundary) return every('unknown');
+ const byId = new Map(admitted.constituents.map((k, i) => [k.contentId, i]));
+ const seen = new Map();
+ for (const p of framed.parts) {
+ const line = /^HTTP\/1\.1 ([1-5][0-9]{2})(?: [^\r\n]*)?$/.exec(p.start);
+ if (!line || !byId.has(p.contentId) || seen.has(p.contentId)) return every('unknown');
+ p.status = Number(line[1]);
+ seen.set(p.contentId, p);
+ }
+ let failure;
+ if (batchStatus < 200 || batchStatus >= 300) {
+ // The atomic failure the service reports: the outer status repeated by ONE part of the set, with its error envelope.
+ const [p] = framed.parts;
+ if (framed.parts.length === 1 && p.status === batchStatus) {
+ let code;
+ try {
+ const env = JSON.parse(p.bodyLines.join('\n'));
+ if (isPlain(env) && isPlain(env.error) && typeof env.error.code === 'string' && /^0x[0-9A-Fa-f]{8}$/.test(env.error.code)) code = env.error.code.toLowerCase();
+ } catch {
+ code = undefined;
+ }
+ failure = { contentId: p.contentId, status: p.status, ...(code ? { code } : {}) };
+ }
+ }
+ const parts = admitted.constituents.map((k) => {
+ const p = seen.get(k.contentId);
+ return p ? judgePart(p, k, admitted, answerOf) : { outcome: 'unknown', status: null };
+ });
+ const complete = batchStatus === 200 && seen.size === n && parts.every((p) => p.outcome === 'acknowledged');
+ const out = parts.map((p) => (complete || p.outcome === 'conflict' ? p : { ...p, outcome: 'unknown' }));
+ return { batchStatus, parts: out, ...(failure ? { failure } : {}) };
+}
+
+module.exports = {
+ MAX_BATCH_PARTS,
+ ROLES,
+ batchConfig,
+ parseCustomApiChangeset,
+ constituentFault,
+ readChangesetAnswer,
+};
diff --git a/plugins/model-apps/scripts/lib/managed-create-context.js b/plugins/model-apps/scripts/lib/managed-create-context.js
new file mode 100644
index 000000000..762b937c1
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/managed-create-context.js
@@ -0,0 +1,581 @@
+'use strict';
+// The shared lifecycle of a protected create set: prepare -> send in scope -> prove -> receipts -> commit, and the
+// read-only recovery of an attempt an earlier run left pending (classifyRecovery: its recovery table).
+//
+// It is GENERIC over the row families of lib/managed-bindings.js (`rowProtocol` attempts). A driver (configuration
+// rows, keyed commands) supplies what only it knows:
+// - the plan of each group: its rows (ids already reserved), each row's expected semantic hash, completion members,
+// rule state and effects (buildRowPlan turns that into the store's prepare plan and the expected proof);
+// - the classifier of its requests (lib/managed-create-transport.js runWithManagedCreateSet `classify`);
+// - a FRESH read of every prepared row, member and rule state (the observation, below), from an isolated reader —
+// never the SDK's retained local copy;
+// - the code a bound row found absent halts with (`notFoundCode`), and, if its approval tokens differ from the
+// default spelling, `approvalTokenOf`.
+// This module never sends a request and never reads the service. It decides, from the persisted attempt, the
+// in-memory answers of this process, and the driver's observation, what may be committed, and commits it.
+//
+// The observation of one attempt (all ids as GUIDs):
+// {
+// rows: [{ kind, key, id, state: 'present' | 'absent' | 'unknown', parentId, projectionSha256,
+// privateState?: 'match' | 'mismatch' | 'masked' | 'unknown' }],
+// members: [{ id, state: 'present' | 'absent' | 'unknown' }],
+// ruleState: 'published' | 'unpublished' | 'unknown' | null,
+// }
+// `projectionSha256` is the driver's semantic projection of the row as read, comparable to the plan's
+// `expectedSha256`; it never covers a private value. `privateState` is required only for a `sensitiveInput` row: whether
+// the readable private value matches what the declaration asks for today (the value itself never reaches this module).
+// A row of the protocol the observation does not list is an unknown read.
+
+const crypto = require('node:crypto');
+const { canonicalJson, normalizeGuid } = require('./reconcile-common.js');
+const { ROW_PROOF_SCHEMA, ROOT_KIND, CODES: STORE_CODES, attemptProvenUnsent, readOnlyCapture } = require('./managed-bindings.js');
+const { runWithManagedCreateSet } = require('./managed-create-transport.js');
+
+const CODES = Object.freeze({
+ intentChanged: 'managed-pending-intent-changed',
+ unverified: 'create-identity-unverified',
+ conflict: 'create-identity-conflict',
+ completion: 'create-completion-required',
+ ownership: 'create-ownership-required',
+});
+
+const sha = (value) => crypto.createHash('sha256').update(canonicalJson(value), 'utf8').digest('hex');
+const rowKey = (kind, key) => `${kind}\u0000${key}`;
+const idKey = (id) => normalizeGuid(id) || String(id).toLowerCase();
+
+/**
+ * The approval token of one row, by default:
+ * root adopt:<family>:<rootKey>
+ * child adopt:<childKind>:<encodeURIComponent(rootKey)>/<encodeURIComponent(slot)>
+ * where a child's binding key is the JSON tuple [rootKey, slot] (e.g. '["contoso_api","request:p"]'). Both parts are
+ * percent-encoded, so a '/' or ':' in a key or slot can never make two rows share a token. A child key that is not such
+ * a tuple has no default token: the driver must pass its own `approvalTokenOf`.
+ */
+function defaultApprovalToken(family, rootKey, row) {
+ if (row.parentId === null) return `adopt:${family}:${rootKey}`;
+ let tuple;
+ try { tuple = JSON.parse(row.key); } catch { tuple = null; }
+ if (!Array.isArray(tuple) || tuple.length !== 2 || tuple[0] !== rootKey || typeof tuple[1] !== 'string' || !tuple[1]) {
+ throw new TypeError(`the ${row.kind} key ${row.key} is not a [rootKey, slot] tuple; the driver must name its approval token`);
+ }
+ return `adopt:${row.kind}:${encodeURIComponent(rootKey)}/${encodeURIComponent(tuple[1])}`;
+}
+
+/**
+ * The expected proof an attempt is marked sending with, derived only from its row protocol (and the base observation of
+ * an edit), so a run that resumes a prepared attempt computes exactly the same proof again:
+ * sentProjectionSha256 the planned rows (kind, key, id, parent, mode, expected semantic hash), sorted;
+ * preservationSha256 the rows the protocol preserves (none for configuration);
+ * children every non-root row, with its parent as namespace and a hash of its (kind, key, id, parent).
+ */
+function expectedOf(root, rowProtocol, baseObservation = null) {
+ const planned = rowProtocol.rows
+ .map((r) => ({ kind: r.kind, key: r.key, id: r.id, parentId: r.parentId, mode: r.mode, expectedSha256: r.expectedSha256 }))
+ .sort((a, b) => (rowKey(a.kind, a.key) < rowKey(b.kind, b.key) ? -1 : 1));
+ return {
+ proofVersion: 1, proofSchema: ROW_PROOF_SCHEMA, rootId: root.id, baseProofSha256: null,
+ sentProjectionSha256: sha(planned), preservationSha256: sha({ preserved: rowProtocol.preserved }), baseObservation,
+ children: rowProtocol.rows.filter((r) => r.parentId !== null).map((r) => ({
+ kind: r.kind, key: r.key, namespaceParentId: r.parentId, id: r.id,
+ associationSha256: sha({ kind: r.kind, key: r.key, id: r.id, parentId: r.parentId }),
+ })),
+ };
+}
+
+/**
+ * A driver's plan of one group -> { prepare, expected }: `prepare` is what managed-bindings.js prepareAttemptSet takes,
+ * `expected` the proof markAttemptSetSending takes. plan = {
+ * family, key, baseGeneration?, revision?, declarationSha256, completionBytes?,
+ * rows: [{ kind, key, id, parentId, mode: 'create' | 'update', expectedSha256, sensitiveInput? }], root first or not;
+ * the root is the row of the family's root kind with no parent;
+ * members?: [{ kind, id, componentType }], ruleState?: 'published' | 'unpublished' | null,
+ * effects?: [{ kind: 'membership' | 'rule-state', id }],
+ * baseObservation?: { rowVersion, savedSha256 } | null (an edit of a bound root records what it read)
+ * }
+ */
+function buildRowPlan(plan) {
+ if (!plan || !Array.isArray(plan.rows) || plan.rows.length === 0) throw new TypeError('a create-set plan names its rows');
+ const rows = plan.rows.map((r) => ({
+ kind: r.kind, key: r.key, id: normalizeGuid(r.id), parentId: r.parentId === null || r.parentId === undefined ? null : normalizeGuid(r.parentId),
+ mode: r.mode, expectedSha256: r.expectedSha256, sensitiveInput: r.sensitiveInput === true, sentFields: null, sentSha256: null, dispatched: false,
+ }));
+ const rootRow = rows.find((r) => r.parentId === null && r.kind === ROOT_KIND[plan.family]);
+ if (!rootRow) throw new TypeError(`the plan of the managed ${plan.family} "${plan.key}" has no root row`);
+ const root = { kind: rootRow.kind, key: rootRow.key, id: rootRow.id };
+ const rowProtocol = {
+ version: 1, rows, preserved: [],
+ completion: { ruleState: plan.ruleState === undefined ? null : plan.ruleState, members: (plan.members || []).map((m) => ({ kind: m.kind, id: normalizeGuid(m.id), componentType: m.componentType })) },
+ effects: (plan.effects || []).map((e) => ({ kind: e.kind, id: normalizeGuid(e.id), dispatched: false })),
+ cohort: null,
+ };
+ const prepare = {
+ family: plan.family, key: plan.key, baseGeneration: plan.baseGeneration === undefined ? null : plan.baseGeneration, root,
+ declarationSha256: plan.declarationSha256, rowProtocol,
+ ...(plan.revision !== undefined ? { revision: plan.revision } : {}), ...(plan.completionBytes !== undefined ? { completionBytes: plan.completionBytes } : {}),
+ };
+ return { prepare, expected: expectedOf(root, rowProtocol, plan.baseObservation === undefined ? null : plan.baseObservation) };
+}
+
+function halt(code, message, rows = [], extra = {}) {
+ return { action: 'halt', code, message, rows, ...extra };
+}
+
+/**
+ * Decide one pending attempt, read-only, by this recovery table; the first row that applies wins:
+ * 1. the declaration it was prepared for differs from today's -> halt managed-pending-intent-changed
+ * 2. prepared, or sending and provably nothing it sent was applied -> resume ('first' / 'continue'), same ids
+ * 3. any row, member or rule state could not be read -> halt create-identity-unverified
+ * 4. a row the group already binds is absent -> halt `notFoundCode`
+ * 5. a present row differs from the original expectation or parent,
+ * or an answer of this process named another id -> halt create-identity-conflict
+ * 6. a planned row absent, a member missing, the rule state not the
+ * original plan's, or a private input not proved -> halt create-completion-required
+ * 7. a row with no ownership (no acknowledgement, receipt, existing
+ * binding or exact approval) -> halt create-ownership-required, with tokens
+ * 8. otherwise -> commit, with each row's origin
+ * opts = { declarationSha256, approvals: Set, boundRecords, facts, notFoundCode, approvalTokenOf, effects }.
+ * `facts` are this process's in-memory answers for the attempt (runWithManagedCreateSet); an earlier process's are gone,
+ * and only the persisted acknowledgement and receipts stand for them.
+ */
+function classifyRecovery(attempt, observation, opts) {
+ const { declarationSha256, approvals = new Set(), boundRecords = [], facts = [], notFoundCode, approvalTokenOf = defaultApprovalToken, effects = [] } = opts || {};
+ if (typeof notFoundCode !== 'string' || !notFoundCode) throw new TypeError('classifyRecovery needs the driver\'s notFoundCode');
+ const name = `the managed ${attempt.family} "${attempt.key}"`;
+ if (declarationSha256 !== attempt.declarationSha256) {
+ return halt(CODES.intentChanged, `${name} has a pending attempt prepared for another declaration; restore the original declaration and run again`);
+ }
+ if (attempt.phase === 'prepared') return { action: 'resume', claim: 'first' };
+ if (attemptProvenUnsent(attempt, effects)) return { action: 'resume', claim: 'continue' };
+ return judgeRows(attempt, observation, { approvals, boundRecords, facts, notFoundCode, approvalTokenOf });
+}
+
+/**
+ * Rows 3-8 of the recovery table (classifyRecovery), for an attempt rows 1-2 did not settle — or, `readOnly: true`, for
+ * a plan of existing rows a read-only acceptance (acceptReadOnly) never sent: then no answer or receipt counts, so every
+ * row is either already bound (its origin kept) or adopted under its own exact approval.
+ */
+function judgeRows(attempt, observation, { approvals = new Set(), boundRecords = [], facts = [], notFoundCode, approvalTokenOf = defaultApprovalToken, readOnly = false } = {}) {
+ const name = `the managed ${attempt.family} "${attempt.key}"`;
+ const p = attempt.rowProtocol;
+ const obsRows = new Map(((observation && observation.rows) || []).map((r) => [rowKey(r.kind, r.key), r]));
+ const bound = new Map(boundRecords.map((r) => [rowKey(r.kind, r.key), r]));
+ const rows = p.rows.map((r) => ({ row: r, seen: obsRows.get(rowKey(r.kind, r.key)) || { state: 'unknown' }, rec: bound.get(rowKey(r.kind, r.key)) || null }));
+ const ids = (list) => list.map(({ row }) => ({ kind: row.kind, key: row.key, id: row.id }));
+ const members = new Map(((observation && observation.members) || []).map((m) => [normalizeGuid(m.id), m.state]));
+ const ruleState = observation ? observation.ruleState : undefined;
+
+ // 3. Unknown reads first: a failed read never proves absence or a difference.
+ const unknownRows = rows.filter(({ seen }) => seen.state !== 'present' && seen.state !== 'absent');
+ const unknownMembers = p.completion.members.filter((m) => { const s = members.get(m.id); return s !== 'present' && s !== 'absent'; });
+ const unknownRule = p.completion.ruleState !== null && ruleState !== 'published' && ruleState !== 'unpublished';
+ if (unknownRows.length || unknownMembers.length || unknownRule) {
+ return halt(CODES.unverified, `${name} could not be read completely; nothing is created or bound`, ids(unknownRows));
+ }
+ // 4. A bound row gone: no replacement, no namesake.
+ const lost = rows.filter(({ seen, rec }) => rec && seen.state === 'absent');
+ if (lost.length) return halt(notFoundCode, `${name} binds a row that no longer exists; it is not replaced`, ids(lost));
+ // 5. Wrong content, wrong parent, or an answer that named another id.
+ const conflictFacts = new Set(facts.filter((f) => f.type === 'row' && f.outcome === 'conflict').map((f) => rowKey(f.kind, f.key)));
+ const differs = rows.filter(({ row, seen }) => conflictFacts.has(rowKey(row.kind, row.key)) || (seen.state === 'present'
+ && (normalizeGuid(seen.id) !== row.id || (seen.parentId ? normalizeGuid(seen.parentId) : null) !== row.parentId || seen.projectionSha256 !== row.expectedSha256)));
+ if (differs.length) return halt(CODES.conflict, `${name} has a row that is not the one its attempt prepared; it is neither overwritten nor adopted`, ids(differs));
+ // 6. Anything not complete after a possible write: never replayed automatically.
+ const absent = rows.filter(({ seen }) => seen.state === 'absent');
+ const missingMembers = p.completion.members.filter((m) => members.get(m.id) !== 'present');
+ const wrongRule = p.completion.ruleState !== null && ruleState !== p.completion.ruleState;
+ const ackFact = (row) => facts.some((f) => f.type === 'row' && f.kind === row.kind && f.key === row.key && f.outcome === 'acknowledged');
+ // A private input is proved only by this process's own acknowledged send plus a matching fresh read, or, across
+ // processes, by the maker's exact approval of a value that is readable and matches today (approval below). A masked,
+ // unreadable or different value is never certified, approval or not.
+ const privateOpen = rows.filter(({ row, seen }) => row.sensitiveInput && seen.privateState !== 'match');
+ if (absent.length || missingMembers.length || wrongRule || privateOpen.length) {
+ return halt(CODES.completion, `${name} is not complete (missing rows, solution membership, rule state or a private input); complete it under the same ids, then run again`,
+ ids([...absent, ...privateOpen]), { phase: missingMembers.length ? 'membership-pending' : wrongRule ? 'state-pending' : 'saved' });
+ }
+ // 7. Ownership, row by row: a parent's acknowledgement or approval never stands in for a child.
+ const createEdit = attempt.expected && attempt.expected.baseObservation === null;
+ const receipt = attempt.acknowledgedChildCreates || [];
+ const decided = [];
+ const missing = [];
+ const rootKey = attempt.root.key;
+ for (const { row, rec } of rows) {
+ const token = approvalTokenOf(attempt.family, rootKey, row);
+ const approved = approvals.has(token);
+ const isRoot = row.parentId === null;
+ const freshAck = !readOnly && row.mode === 'create' && ackFact(row) && (!isRoot || createEdit);
+ const persistedAck = !readOnly && (isRoot ? attempt.acknowledgedRoot === true : receipt.some((c) => c.kind === row.kind && c.key === row.key && normalizeGuid(c.id) === row.id));
+ // A private input this process saw saved (a create or an edit) is proved by that answer plus the matching fresh read.
+ // Across processes the answer is gone: only the maker's exact approval accepts today's readable, matching value as
+ // the new baseline (never a claim to have confirmed the old send).
+ const privateNeedsApproval = row.sensitiveInput && !ackFact(row);
+ if (rec) {
+ if (privateNeedsApproval && !approved) { missing.push({ row, token }); continue; }
+ decided.push({ row, origin: rec.origin, bound: true, receipt: false });
+ } else if ((freshAck || persistedAck) && (!privateNeedsApproval || approved)) {
+ decided.push({ row, origin: 'created', bound: false, receipt: freshAck && !persistedAck });
+ } else if (approved) {
+ decided.push({ row, origin: 'adopted', bound: false, receipt: false });
+ } else {
+ missing.push({ row, token });
+ }
+ }
+ if (missing.length) {
+ return halt(CODES.ownership, `${name} matches its attempt exactly, but ${missing.length} row(s) were never acknowledged as created by it; approve each exact token to manage them`,
+ ids(missing), { approvals: missing.map((m) => m.token) });
+ }
+ return { action: 'commit', rows: decided };
+}
+
+/**
+ * The context of one invocation over one store:
+ * createManagedCreateContext({ store, approvals, notFoundCode, approvalTokenOf?, recordOf? })
+ * `approvals` is the invocation's set (or list) of typed authorization tokens; `recordOf(row, origin, attempt, header)`
+ * may replace the default binding record (a driver whose rows nest deeper than root -> child).
+ */
+function createManagedCreateContext({ store, approvals = [], notFoundCode, approvalTokenOf = defaultApprovalToken, recordOf } = {}) {
+ if (!store || typeof store.prepareAttemptSet !== 'function') throw new TypeError('createManagedCreateContext needs the managed binding store');
+ if (typeof notFoundCode !== 'string' || !notFoundCode) throw new TypeError('createManagedCreateContext needs the driver\'s notFoundCode');
+ const approved = approvals instanceof Set ? approvals : new Set(approvals);
+ const facts = new Map();
+ const begun = new Set();
+ // The receipt-store failure that stopped this context (run): nothing more is sent under it.
+ let stopped = null;
+
+ const accepts = (check, value) => {
+ try { return check(value) === true; } catch { return false; }
+ };
+ // The root receipt of a checked run (run): for each attempt of the run whose root THIS run created — a create of a
+ // new root (no base observation), not already receipted, its root row's own fact acknowledged under the root's id —
+ // one noteSaved at the epoch the run was sent under. The store re-checks the epoch, the root and its create mode.
+ function receiptRoots(attempts, rowFacts) {
+ store.refresh();
+ const env = snapshot();
+ for (const { token, epoch } of attempts) {
+ const a = env.attempts.find((x) => x.token === token);
+ if (!a || !a.rowProtocol || a.acknowledgedRoot || !a.expected || a.expected.baseObservation !== null) continue;
+ const root = a.rowProtocol.rows.find((r) => r.parentId === null && r.kind === a.root.kind && r.key === a.root.key);
+ if (!root || root.mode !== 'create' || idKey(root.id) !== idKey(a.root.id)) continue;
+ const fact = rowFacts.find((f) => f.token === token && f.kind === root.kind && f.key === root.key);
+ if (!fact || fact.outcome !== 'acknowledged' || fact.mode !== 'create' || idKey(fact.id) !== idKey(root.id)) continue;
+ store.noteSaved(token, { proof: null, acknowledgedRoot: true, phase: 'sending', epoch });
+ }
+ }
+
+ const snapshot = () => store.snapshot().envelope;
+ const attemptOf = (env, token) => {
+ const a = env.attempts.find((x) => x.token === token);
+ if (!a) throw Object.assign(new Error('the create set names an attempt the store does not hold'), { code: 'managed-not-settled' });
+ return a;
+ };
+
+ function defaultRecord(row, origin, attempt, header) {
+ return {
+ formatVersion: 1, appUniqueName: header.appUniqueName, environmentFingerprint: header.environmentFingerprint,
+ kind: row.kind, key: row.key, id: row.id, intentSha256: row.expectedSha256, origin,
+ ...(row.parentId !== null ? { parentKey: attempt.root.key } : {}),
+ };
+ }
+
+ function proposalOf(attempt, observation, decided, env) {
+ const header = { appUniqueName: env.appUniqueName, environmentFingerprint: env.environmentFingerprint };
+ const group = env.groups.find((g) => g.family === attempt.family && g.key === attempt.key) || null;
+ const seen = new Map(observation.rows.map((r) => [rowKey(r.kind, r.key), r]));
+ const records = decided.map(({ row, origin, bound }) => {
+ if (!bound) return (recordOf || defaultRecord)(row, origin, attempt, header);
+ // A bound row is recorded again with the intent this attempt proved (an edit changes what the row should be), but
+ // never under another identity or origin: the row it binds and how it was first bound are history, not intent.
+ const old = group.records.find((r) => r.kind === row.kind && r.key === row.key);
+ const next = (recordOf || defaultRecord)(row, old.origin, attempt, header);
+ if (!next || next.kind !== old.kind || next.key !== old.key || idKey(next.id) !== idKey(old.id) || next.origin !== old.origin) {
+ throw new TypeError(`the record of the bound ${row.kind} "${row.key}" must keep its kind, key, id and origin`);
+ }
+ return next;
+ });
+ const observed = attempt.rowProtocol.rows.map((r) => {
+ const s = seen.get(rowKey(r.kind, r.key));
+ return { kind: r.kind, key: r.key, id: r.id, parentId: r.parentId, projectionSha256: s.projectionSha256, sensitiveInput: r.sensitiveInput };
+ });
+ const children = attempt.expected.children;
+ // The consumer state is the last confirmed baseline of every row the group binds, and the store keeps every record
+ // an attempt does not name. A row this attempt omitted (an update of the root alone) was not observed now, so it
+ // keeps the baseline it was last confirmed with, unchanged under its retained identity, and is never restamped
+ // as freshly observed. The saved proof stays over the rows this attempt observed.
+ const fresh = new Set(observed.map((r) => rowKey(r.kind, r.key)));
+ const prior = group && group.consumerState && Array.isArray(group.consumerState.rows) ? group.consumerState.rows : [];
+ const carried = prior.filter((r) => !fresh.has(rowKey(r.kind, r.key))).map((r) => ({ ...r }));
+ return {
+ token: attempt.token, baseGeneration: attempt.baseGeneration, proofSchema: ROW_PROOF_SCHEMA, records,
+ proof: {
+ savedSha256: sha(observed.map(({ kind, key, id, parentId, projectionSha256 }) => ({ kind, key, id, parentId, projectionSha256 }))),
+ semanticSha256: sha({ rows: attempt.rowProtocol.rows.map((r) => ({ kind: r.kind, key: r.key, expectedSha256: r.expectedSha256 })), completion: attempt.rowProtocol.completion }),
+ preservationSha256: attempt.expected.preservationSha256,
+ expectedChildrenSha256: children.length ? sha(children) : null,
+ },
+ consumerState: { version: 1, rows: [...observed, ...carried] },
+ adoptionApproved: decided.some(({ row, origin, bound }) => !bound && row.parentId === null && origin === 'adopted'),
+ adoptionApprovedChildren: decided.filter(({ row, origin, bound }) => !bound && row.parentId !== null && origin === 'adopted').map(({ row }) => ({ kind: row.kind, key: row.key, id: row.id })),
+ };
+ }
+
+ return {
+ /** Prepare every plan (buildRowPlan input) in ONE write, then mark them sending in ONE write: [{ family, key, token, epoch, expected }]. */
+ begin(plans) {
+ const built = plans.map(buildRowPlan);
+ const tokens = store.prepareAttemptSet(built.map((b) => b.prepare));
+ const marked = store.markAttemptSetSending(tokens.map((token, i) => ({ token, expected: built[i].expected })), { claim: 'first', observed: true });
+ return marked.map(({ token, epoch }, i) => { begun.add(token); return { family: built[i].prepare.family, key: built[i].prepare.key, token, epoch, expected: built[i].expected }; });
+ },
+ /**
+ * Claim attempts classifyRecovery answered `resume` for, under the same ids and a new fenced epoch: entries
+ * [{ token, claim: 'first' | 'continue', baseObservation? }]. A sent attempt keeps the proof it was sent with; a
+ * prepared one's is recomputed from its persisted protocol (with the edit's fresh `baseObservation`, if any).
+ */
+ resume(entries) {
+ store.refresh();
+ const env = snapshot();
+ const out = [];
+ for (const claim of ['first', 'continue']) {
+ const these = entries.filter((e) => e.claim === claim);
+ if (!these.length) continue;
+ const marks = these.map(({ token, baseObservation = null }) => {
+ const a = attemptOf(env, token);
+ return { token, expected: a.expected || expectedOf(a.root, a.rowProtocol, baseObservation) };
+ });
+ for (const m of store.markAttemptSetSending(marks, { claim, observed: true })) {
+ begun.add(m.token);
+ const a = attemptOf(env, m.token);
+ out.push({ family: a.family, key: a.key, token: m.token, epoch: m.epoch, expected: marks.find((x) => x.token === m.token).expected });
+ }
+ }
+ return out;
+ },
+ /**
+ * Claim the one completion effect `{ kind, id }` of the attempt `token` that its record proves was never dispatched
+ * (store.claimUnsentRowEffect: a saved rule create's initial publication), under a new fenced epoch. Answers the
+ * entry `run` takes: { family, key, token, epoch, expected }.
+ */
+ claimEffect(token, { kind, id }) {
+ const { epoch } = store.claimUnsentRowEffect({ token, kind, id });
+ store.refresh();
+ const a = attemptOf(snapshot(), token);
+ begun.add(token);
+ return { family: a.family, key: a.key, token, epoch, expected: a.expected };
+ },
+ /**
+ * Run `fn` in the request scope of `attempts` (what begin/resume answered); keeps the answers per attempt.
+ * `acceptResult(value)` is the driver's check of what `fn` answered (acceptSaved for an SDK push): the run is CHECKED
+ * only when it answers exactly `true` (a throw is false), `fn` threw nothing, the scope latched no local failure and
+ * every row request it sent was acknowledged (none unknown, unanswered or naming another row). No `acceptResult`
+ * means no checked run. Only a checked run's acknowledgements are kept as such: in any other run each one is kept as
+ * `unchecked` — a 2xx for one request of an operation that failed, or whose result nobody checked, proves no create —
+ * while a conflict or an unknown answer is kept exactly as it was.
+ * Right after a checked run, before any read-back or membership request, every root it created is receipted in the
+ * store (noteSaved, the attempt staying sending): a root create this run saw acknowledged and checked, of an attempt
+ * still at the epoch it was sent under. A receipt the store cannot write is this run's `localError` (typed, never a
+ * network retry), its acknowledgements are kept unchecked, and every later run of this context is refused unsent.
+ * Answers runWithManagedCreateSet's { value, error, localError, facts } and `checked`. `batch` is passed to it as given
+ * (the one Custom API change set a set may send, see runWithManagedCreateSet); an API PATCH in it is an update, so
+ * it never receipts a root.
+ */
+ async run({ attempts, classify, deleteCode, label, acceptResult, batch }, fn) {
+ if (stopped) return { value: undefined, error: null, localError: stopped, facts: [], checked: false };
+ const outcome = await runWithManagedCreateSet({ store, entries: attempts.map(({ token, epoch }) => ({ token, epoch })), classify, deleteCode, label, batch }, fn);
+ const rowFacts = outcome.facts.filter((f) => f.type === 'row');
+ let localError = outcome.localError;
+ let checked = typeof acceptResult === 'function' && outcome.error === null && localError === null
+ && rowFacts.every((f) => f.outcome === 'acknowledged') && accepts(acceptResult, outcome.value);
+ if (checked) {
+ try {
+ receiptRoots(attempts, rowFacts);
+ } catch (e) {
+ stopped = e;
+ localError = e;
+ checked = false;
+ }
+ }
+ for (const f of outcome.facts) {
+ if (!facts.has(f.token)) facts.set(f.token, []);
+ facts.get(f.token).push(!checked && f.type === 'row' && f.outcome === 'acknowledged' ? { ...f, outcome: 'unchecked' } : f);
+ }
+ return { ...outcome, localError, checked };
+ },
+ /** This process's in-memory answers for one attempt. */
+ facts(token) {
+ return (facts.get(token) || []).slice();
+ },
+ /**
+ * Release `attempt` (what begin/resume answered) after its run stopped before anything left — the operation was refused
+ * before its first request — so it does not hold its group for a declaration that is never sent (store
+ * retireProvenUnsentAttempt: only at the epoch this run holds, and only while the attempt's own record proves nothing
+ * it may have sent can land). Best effort: answers true when it was released, false when the store kept it (it may
+ * have been sent, another run claimed it, or the store could not be written), so it stays on its recovery path and
+ * the caller's own stop stands.
+ */
+ release(attempt) {
+ try {
+ store.retireProvenUnsentAttempt({ token: attempt.token, epoch: attempt.epoch });
+ begun.delete(attempt.token);
+ facts.delete(attempt.token);
+ return true;
+ } catch {
+ return false;
+ }
+ },
+ /** classifyRecovery for the persisted attempt `token`, with this context's approvals, answers and bindings. */
+ classify(token, observation, { declarationSha256 } = {}) {
+ store.refresh();
+ const env = snapshot();
+ const a = attemptOf(env, token);
+ const group = env.groups.find((g) => g.family === a.family && g.key === a.key) || null;
+ return classifyRecovery(a, observation, {
+ declarationSha256: declarationSha256 === undefined && begun.has(token) ? a.declarationSha256 : declarationSha256,
+ approvals: approved, boundRecords: group ? group.records : [], facts: facts.get(token) || [], notFoundCode, approvalTokenOf,
+ effects: env.workflowEffects,
+ });
+ },
+ /**
+ * Settle each item { token, observation, declarationSha256? } on its own, in order: record the child receipts this
+ * process proved (noteSaved: a child create a checked run saw acknowledged and the fresh read found exact; a root's
+ * receipt was already written by that run), then commit the item when it is
+ * complete. One item's halt never stops an earlier or later item's commit (configuration groups are independent);
+ * a store failure (busy, full, write failed) throws, typed. Answers [{ family, key, token, verdict, group? }].
+ */
+ settle(items) {
+ const results = [];
+ for (const { token, observation, declarationSha256 } of items) {
+ let verdict = this.classify(token, observation, { declarationSha256 });
+ let env = snapshot();
+ let a = attemptOf(env, token);
+ // Receipts are what THIS process saw acknowledged and a fresh read then found exactly as prepared; they are kept
+ // with the attempt, so a later run (or this item's ownership halt) still has them.
+ const exact = (row) => {
+ const s = observation && observation.rows.find((r) => r.kind === row.kind && r.key === row.key);
+ return s && s.state === 'present' && normalizeGuid(s.id) === row.id && (s.parentId ? normalizeGuid(s.parentId) : null) === row.parentId && s.projectionSha256 === row.expectedSha256;
+ };
+ const mine = facts.get(token) || [];
+ const acked = (row) => row.mode === 'create' && mine.some((f) => f.type === 'row' && f.kind === row.kind && f.key === row.key && f.outcome === 'acknowledged')
+ && !mine.some((f) => f.type === 'row' && f.kind === row.kind && f.key === row.key && f.outcome === 'conflict');
+ // A root create is receipted by the checked run itself (run); only children wait for this fresh exact read.
+ const have = a.acknowledgedChildCreates || [];
+ const childReceipts = a.rowProtocol.rows.filter((r) => r.parentId !== null && acked(r) && exact(r) && !have.some((c) => c.kind === r.kind && c.key === r.key))
+ .map((r) => ({ kind: r.kind, key: r.key, id: r.id }));
+ if (verdict.action !== 'resume' && verdict.code !== CODES.intentChanged && childReceipts.length) {
+ store.noteSaved(token, { proof: { savedSha256: sha((observation.rows || []).map(({ kind, key, id, projectionSha256 }) => ({ kind, key, id, projectionSha256: projectionSha256 || null }))) }, acknowledgedChildCreates: childReceipts, phase: verdict.phase || 'saved' });
+ verdict = this.classify(token, observation, { declarationSha256 });
+ env = snapshot();
+ a = attemptOf(env, token);
+ }
+ const result = { family: a.family, key: a.key, token, verdict };
+ if (verdict.action === 'commit') {
+ const [group] = store.commitGroupSet([proposalOf(a, observation, verdict.rows, env)]);
+ result.group = group;
+ }
+ results.push(result);
+ }
+ return results;
+ },
+ /**
+ * What a read-only acceptance (acceptReadOnly) is later checked against, taken BEFORE the fresh read that proves its
+ * rows: one capture per token (managed-bindings.js readOnlyCapture), from a fresh read of the store.
+ */
+ captureReadOnly(tokens) {
+ store.refresh();
+ const env = snapshot();
+ return tokens.map((token) => {
+ attemptOf(env, token);
+ return readOnlyCapture(env, token);
+ });
+ },
+ /**
+ * Accept, WITHOUT sending anything, attempts deliberately planned over existing rows only (every row `update`, the
+ * expected proof carrying the base observation it read) and never sent: items [{ token, observation, capture,
+ * declarationSha256? }], `capture` from captureReadOnly before `observation` was read. Each item must be the
+ * declaration it was prepared for, show nothing dispatched, and read back exactly — rows, parents, content, members,
+ * rule state, and a private input readable and matching — with every row the group does not bind approved by its
+ * own exact token (rows 3-8 of the recovery table, with no answer or receipt counted). This is not the generic
+ * recovery of an unsent attempt (classifyRecovery resumes those), and an attempt that may have sent anything is
+ * never accepted here. The items are ONE acceptance: unless every one of them can commit, none is committed and
+ * every attempt stays held; otherwise all commit in one store write (commitReadOnlyGroupSet), which re-checks each
+ * capture and the zero dispatch under its lease, adopts each new record and keeps each bound record's origin.
+ * Answers [{ family, key, token, verdict, group? }].
+ */
+ acceptReadOnly(items) {
+ store.refresh();
+ const env = snapshot();
+ const results = [];
+ const proposals = [];
+ for (const { token, observation, capture, declarationSha256 } of items) {
+ const { a, verdict } = readOnlyVerdict(env, { token, observation, declarationSha256 });
+ if (!capture || capture.token !== token) throw new TypeError(`the managed ${a.family} "${a.key}" has no capture taken before its fresh read (captureReadOnly)`);
+ results.push({ family: a.family, key: a.key, token, verdict });
+ if (verdict.action === 'commit') proposals.push({ ...proposalOf(a, observation, verdict.rows, env), capture });
+ }
+ if (proposals.length !== items.length) return results;
+ const groups = store.commitReadOnlyGroupSet(proposals);
+ results.forEach((r, i) => { r.group = groups[i]; });
+ return results;
+ },
+ /**
+ * The verdict acceptReadOnly would give each item [{ token, observation, declarationSha256? }], judged exactly as it
+ * judges (the declaration, the zero dispatch, then rows 3-8 with no answer or receipt counted), WITHOUT committing
+ * anything: a read-only preflight names the halt before the build sends anything, and a commit here is only a
+ * forecast — the acceptance itself re-reads, re-captures and re-judges. Answers [{ family, key, token, verdict }].
+ */
+ judgeReadOnly(items) {
+ store.refresh();
+ const env = snapshot();
+ return items.map(({ token, observation, declarationSha256 }) => {
+ const { a, verdict } = readOnlyVerdict(env, { token, observation, declarationSha256 });
+ return { family: a.family, key: a.key, token, verdict };
+ });
+ },
+ };
+
+ // One item of a read-only acceptance, judged (acceptReadOnly, judgeReadOnly). Throws when the attempt is not a plan of
+ // existing rows with a base observation: only such a plan is ever accepted without a send.
+ function readOnlyVerdict(env, { token, observation, declarationSha256 }) {
+ const a = attemptOf(env, token);
+ const name = `the managed ${a.family} "${a.key}"`;
+ if (!a.rowProtocol || !a.expected || !a.expected.baseObservation || a.rowProtocol.rows.some((r) => r.mode !== 'update')) {
+ throw new TypeError(`${name} is not a plan of existing rows with a base observation; only such a plan is accepted without a send`);
+ }
+ const declared = declarationSha256 === undefined && begun.has(token) ? a.declarationSha256 : declarationSha256;
+ const group = env.groups.find((g) => g.family === a.family && g.key === a.key) || null;
+ let verdict;
+ if (declared !== a.declarationSha256) {
+ verdict = halt(CODES.intentChanged, `${name} has a pending attempt prepared for another declaration; restore the original declaration and run again`);
+ } else if (!attemptProvenUnsent(a, env.workflowEffects)) {
+ verdict = halt(STORE_CODES.pending, `${name} attempt may have sent something; it is recovered from its original expectation, never accepted read-only`);
+ } else {
+ verdict = judgeRows(a, observation, { approvals: approved, boundRecords: group ? group.records : [], notFoundCode, approvalTokenOf, readOnly: true });
+ }
+ return { a, verdict };
+ }
+}
+
+/**
+ * The `acceptResult` of a run (createManagedCreateContext run) for the SDK's pushArtifact: the result proves a checked
+ * save only when it says `saved: true` for exactly the artifact the run pushed — the expected `type` and `id` (a GUID in
+ * any spelling; a command bar's id is its table name, compared exactly) — and carries no error. A refused
+ * ({ saved: false, error }), adopted-existing, no-op, malformed or missing result proves nothing.
+ * { type, id, saved: true, shipped, publish, ... } a save: accepted
+ * { type, id, saved: false, adoptedExisting: true, ... } an existing artifact taken over: not a create
+ * { type, id, saved: false, shipped: false, publish, error: { code } } a refusal (ALREADY_EXISTS, VERSION_CONFLICT, ...)
+ */
+function acceptSaved({ type, id } = {}) {
+ if (typeof type !== 'string' || !type || typeof id !== 'string' || !id) throw new TypeError('acceptSaved needs the artifact type and id the run pushes');
+ const want = normalizeGuid(id) || id;
+ return (result) => !!result && typeof result === 'object' && !Array.isArray(result)
+ && result.saved === true && result.adoptedExisting !== true && (result.error === undefined || result.error === null)
+ && result.type === type && typeof result.id === 'string' && (normalizeGuid(result.id) || result.id) === want;
+}
+
+module.exports = {
+ CODES,
+ createManagedCreateContext,
+ classifyRecovery,
+ acceptSaved,
+ buildRowPlan,
+ expectedOf,
+ defaultApprovalToken,
+};
diff --git a/plugins/model-apps/scripts/lib/managed-create-transport.js b/plugins/model-apps/scripts/lib/managed-create-transport.js
new file mode 100644
index 000000000..ec9ae81bc
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/managed-create-transport.js
@@ -0,0 +1,593 @@
+'use strict';
+// The send-once request boundary of a protected create set (configuration rows; also keyed commands, which are not
+// shipped in this release).
+//
+// The plugin's HTTP client is made once per invocation (build-model-app.js makeSdk) and asks ONE gate before every
+// request (lib/sdk-http-client.js createAzHttpClient `workflowEffectGate.screen`):
+// screen({ method, url, body, headers }) -> throw to refuse the request unsent, null to let it pass as any other, or a
+// send handle { dispatching(), answered(res) } that makes the request send-once: `dispatching()` runs synchronously
+// right before the send (a throw leaves it unsent) and `answered(res)` gets { statusCode, headers, body } or { error }.
+// This module is that gate for the managed-binding row protocol (lib/managed-bindings.js `rowProtocol`):
+// - createDeferredManagedCreateGate() is made with the client, before the store is open, and bound ONCE to the
+// invocation's store later (as lib/deferred-workflow-gate.js is for workflow effects);
+// - runWithManagedCreateSet(set, fn) runs `fn` (the SDK operation) inside the scope of the attempts the set prepared
+// and marked sending; only inside such a scope does the gate do anything. Outside one it is inert (null), so every
+// build without a protected set sends exactly what it always sent;
+// - composeWriteGates(...gates) lets this gate and the workflow effect gate share the client's one gate slot.
+// Inside a scope, every mutation must be one the driver's classifier names as a prepared row request or completion
+// effect of the set; the row protocol is sealed and marked dispatched under the store's lease BEFORE the request leaves
+// (managed-bindings.js sealRowDispatch / markRowEffectDispatch). Everything else that writes is refused unsent:
+// - an unbound gate, or a scope over another store (a wiring fault: there is no ungated or random-id fallback);
+// - any DELETE (a protected scope never removes a row; the set names the code, e.g.
+// configuration-protected-removal-unsupported);
+// - a `$batch`, but for the one change set lib/managed-create-batch.js admits when the set opts in with `batch`: a
+// Custom API change set editing the API the set binds and adding new children, every constituent a prepared row of
+// one attempt, sealed together in one store write and sent once (batchHandle). Every other `$batch` is refused;
+// - a mutation the classifier does not recognise, a token outside the set, a row the protocol does not name under
+// that id and parent, or a row or effect already sent once in this scope or by an earlier run.
+// Response facts are kept in memory only, per row and effect (see answerOf); they are evidence a driver turns into
+// receipts after a fresh read (lib/managed-create-context.js), never a binding by themselves.
+// Every local refusal or store failure is also recorded in the scope: the SDK may catch the thrown error and report its
+// own (or nothing), so runWithManagedCreateSet answers the FIRST local failure as `localError`, and a caller must surface
+// it as the typed local failure it is — never as a network error to retry, and never as a saved result.
+
+const crypto = require('node:crypto');
+const { AsyncLocalStorage } = require('node:async_hooks');
+const { canonicalJson, normalizeGuid } = require('./reconcile-common.js');
+const { apiPath } = require('./workflow-effect-context.js');
+const { MAX_BATCH_PARTS, ROLES: BATCH_ROLES, batchConfig, parseCustomApiChangeset, constituentFault, readChangesetAnswer } = require('./managed-create-batch.js');
+
+const MISMATCH = 'managed-create-request-mismatch';
+const HEX64 = /^[0-9a-f]{64}$/;
+const FIELD_NAME = /^[A-Za-z_][A-Za-z0-9_@.]{0,127}$/;
+const als = new AsyncLocalStorage();
+
+function mismatch(message, code = MISMATCH) {
+ return Object.assign(new Error(message), { code });
+}
+
+const isRead = (method) => method === 'GET' || method === 'HEAD';
+
+/**
+ * The non-private projection a request carries for one row, as sealRowDispatch keeps it: the sorted field names and the
+ * sha256 of the canonical JSON of those fields. A driver passes only the fields it may record (never a secret value or
+ * a connection id); `fields` is a plain object of field name -> value.
+ */
+function sentProjection(fields) {
+ const sentFields = Object.keys(fields || {}).sort();
+ const picked = Object.fromEntries(sentFields.map((k) => [k, fields[k]]));
+ return { sentFields, sentSha256: crypto.createHash('sha256').update(canonicalJson(picked), 'utf8').digest('hex') };
+}
+
+// The identity evidence of one answer to a create, in the three places the Web API may put it:
+// OData-EntityId: https://contoso.crm.dynamics.com/api/data/v9.2/customapis(5e4a0b1c-0000-4000-8000-000000000001)
+// Location: the same URL (some gateways send it instead, or as well)
+// the body, under Prefer: return=representation: { "customapiid": "5e4a…", "CustomAPIRequestParameters": [{ … }] }
+// EVERY value supplied must agree with the row the request prepared, never just the first one found. A header is read
+// from any spelling of its name; Node folds a repeated header into one value joined by ", ", and some transports hand
+// an array instead, so a comma or a second value is two identities, which cannot be told apart: unknown. An alternate-key
+// URL — customapis(uniquename='contoso_api') — names no GUID, so it proves nothing about the id that was saved: unknown.
+// A body is read only for the expected primary-key field and the children the descriptor names (never for any GUID in
+// it: a lookup carries another row's id). A body that is not JSON, not an object or an OData error envelope is unknown,
+// and so is one in which an object the identity is read from — the body itself, or an element of a child array the
+// descriptor names — has two members of one name (see memberNameRepeats).
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-entity-web-api
+const IDENTITY_HEADERS = ['odata-entityid', 'location'];
+const KEYED_URL = /^([A-Za-z_][A-Za-z0-9_]*)\(([^()]*)\)$/;
+
+function headerIdentities(headers) {
+ const out = [];
+ let ambiguous = false;
+ for (const name of IDENTITY_HEADERS) {
+ const values = [];
+ for (const [k, v] of Object.entries(headers || {})) {
+ if (k.toLowerCase() !== name || v === null || v === undefined) continue;
+ for (const one of Array.isArray(v) ? v : [v]) values.push(String(one));
+ }
+ if (values.length > 1) ambiguous = true;
+ for (const raw of values) {
+ if (raw.includes(',')) { ambiguous = true; continue; }
+ const m = KEYED_URL.exec(apiPath(raw) || '');
+ out.push(m ? { table: m[1].toLowerCase(), inner: m[2] } : { table: null, inner: null });
+ }
+ }
+ return { ids: out, ambiguous };
+}
+
+function bodyOf(raw) {
+ if (raw === undefined || raw === null) return { empty: true };
+ if (typeof raw === 'object' && !Buffer.isBuffer(raw)) return { empty: false, json: raw, text: null };
+ const text = Buffer.isBuffer(raw) ? raw.toString('utf8') : String(raw);
+ if (!text.trim()) return { empty: true };
+ try { return { empty: false, json: JSON.parse(text), text }; } catch { return { empty: false, json: undefined, text }; }
+}
+
+const isPlain = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
+
+// Every object of a JSON text, as { path, names }: the member names it holds, DECODED and in order, and where it sits
+// (the member names and array indexes that lead to it; [] for the top object). JSON.parse keeps only the LAST of two
+// members of one name, and names are compared after their escapes are decoded, so all of these read as one id to
+// JSON.parse while their text carries two:
+// {"customapi\u0069d":"<other>","customapiid":"<guid>"} a key spelled twice
+// {"CustomAPIRequestParameters":[{"customapirequestparameterid":"<other>","uniquename":"p","customapirequestparameterid":"<guid>"}]}
+// {"CustomAPIRequestParameters":[{…<other>…}],"CustomAPIRequestParameters":[{…<guid>…}]} a navigation property twice
+// Called only on text JSON.parse accepted, so the text is well-formed: a string token runs to the first quote that no
+// backslash escapes, and JSON.parse decodes that token exactly as it decoded the member name.
+// See: https://www.rfc-editor.org/rfc/rfc8259#section-4 (names SHOULD be unique; parsers differ when they are not)
+function objectsOf(text) {
+ const found = [];
+ let i = 0;
+ const ws = () => { while (i < text.length && ' \t\r\n'.includes(text[i])) i += 1; };
+ const string = () => {
+ const start = i;
+ i += 1;
+ while (text[i] !== '"') i += text[i] === '\\' ? 2 : 1;
+ i += 1;
+ return JSON.parse(text.slice(start, i));
+ };
+ const value = (path) => {
+ ws();
+ if (text[i] === '{') {
+ i += 1;
+ const names = [];
+ ws();
+ if (text[i] === '}') i += 1;
+ else {
+ for (;;) {
+ ws();
+ const name = string();
+ ws();
+ i += 1; // the colon
+ value([...path, name]);
+ names.push(name);
+ ws();
+ if (text[i++] !== ',') break;
+ }
+ }
+ found.push({ path, names });
+ } else if (text[i] === '[') {
+ i += 1;
+ ws();
+ if (text[i] === ']') { i += 1; return; }
+ for (let n = 0; ; n += 1) {
+ value([...path, n]);
+ ws();
+ if (text[i++] !== ',') break;
+ }
+ } else if (text[i] === '"') {
+ string();
+ } else {
+ while (i < text.length && !',}] \t\r\n'.includes(text[i])) i += 1;
+ }
+ };
+ value([]);
+ return found;
+}
+
+// Whether an object the identity of an answer is read from repeats a member name: the body itself (its primary key,
+// and each child navigation property, may be one of the repeats) or an element of a child array the descriptor names
+// (its key and its match fields). Any repeat there makes the answer ambiguous, whichever name it is. Objects deeper in
+// the body (an expanded lookup) are never read for identity, so a repeat there changes nothing. A text too deeply
+// nested to scan is ambiguous as well: the answer fails closed to unknown.
+function memberNameRepeats(text, arrays) {
+ let objects;
+ try { objects = objectsOf(text); } catch { return true; }
+ return objects.some(({ path, names }) => new Set(names).size !== names.length
+ && (path.length === 0 || (path.length === 2 && arrays.includes(path[0]) && typeof path[1] === 'number')));
+}
+
+/**
+ * What one answer says about a send-once request, kept in memory only:
+ * acknowledged a 2xx (never a 202, which only says the request was queued) whose every identity agrees with the
+ * request: each OData-EntityId and Location header names the expected table and row, the body's
+ * primary key is the expected one, and each child the descriptor names is found once in the body under
+ * its own expected id. An answer with no identity at all acknowledges only as the empty 204 the Web API
+ * documents for a create without return=representation;
+ * conflict a 2xx whose well-formed identity names ANOTHER row or table: the service did not save the row the
+ * request prepared, and it is never taken as a receipt. It wins over anything unknown in the same answer;
+ * unknown no status, a transport error (the request may still have been applied), any non-2xx or 202 answer, or
+ * identity evidence that is malformed, duplicated, ambiguous or incomplete.
+ * `expect`: null for a completion effect (only its status is read); otherwise { id, table?, key?, children? } — the
+ * row the request prepared, its entity set and primary-key field, and [{ id, at, key, match }] for each deep-insert
+ * child to find in the body's `at` array by its `match` fields. A string is taken as { id }.
+ * A non-2xx answer is not treated as "not started" here: only a fresh read decides what is there.
+ */
+function answerOf(res, expect) {
+ const status = res && Number.isInteger(res.statusCode) ? res.statusCode : res && Number.isInteger(res.status) ? res.status : null;
+ if (!res || res.error || status === null) return { outcome: 'unknown', status };
+ if (status < 200 || status >= 300) return { outcome: 'unknown', status };
+ if (expect === null || expect === undefined) return { outcome: 'acknowledged', status };
+ const want = typeof expect === 'string' ? { id: expect } : expect;
+ const wantId = want.id ? normalizeGuid(want.id) : null;
+ const table = typeof want.table === 'string' ? want.table.toLowerCase() : null;
+ let conflict = false;
+ let unknown = status === 202;
+ let seen = 0;
+ let answeredId;
+ const compare = (id) => {
+ seen += 1;
+ if (!id) { unknown = true; return; }
+ if (answeredId === undefined || id !== wantId) answeredId = id;
+ if (wantId && id !== wantId) conflict = true;
+ };
+ const headers = headerIdentities(res.headers);
+ if (headers.ambiguous) unknown = true;
+ for (const h of headers.ids) {
+ if (h.table === null) { seen += 1; unknown = true; continue; }
+ if (table && h.table !== table) { seen += 1; conflict = true; continue; }
+ // customapis(<guid>) or, as some answers spell it, customapis(customapiid=<guid>); any other name=value is an
+ // alternate key and names no id.
+ const named = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(h.inner);
+ if (named && !(want.key && named[1].toLowerCase() === String(want.key).toLowerCase())) { seen += 1; unknown = true; continue; }
+ compare(normalizeGuid(named ? named[2] : h.inner));
+ }
+ const body = bodyOf(res.body);
+ if (!body.empty) {
+ if (!isPlain(body.json) || body.json.error !== undefined) {
+ unknown = true;
+ } else if (want.key) {
+ const key = String(want.key);
+ if (body.text !== null && memberNameRepeats(body.text, (want.children || []).map((c) => c.at))) unknown = true;
+ if (Object.prototype.hasOwnProperty.call(body.json, key)) compare(typeof body.json[key] === 'string' ? normalizeGuid(body.json[key]) : null);
+ for (const c of want.children || []) {
+ const list = body.json[c.at];
+ if (list === undefined) continue;
+ if (!Array.isArray(list)) { unknown = true; continue; }
+ const found = list.filter((x) => isPlain(x) && Object.entries(c.match).every(([f, v]) => x[f] === v));
+ if (found.length !== 1) { unknown = true; continue; }
+ const raw = found[0][c.key];
+ const id = typeof raw === 'string' ? normalizeGuid(raw) : null;
+ if (!id) unknown = true;
+ else if (id !== normalizeGuid(c.id)) conflict = true;
+ }
+ }
+ }
+ if (seen === 0 && !(status === 204 && body.empty)) unknown = true;
+ const extra = answeredId ? { answeredId } : {};
+ if (conflict) return { outcome: 'conflict', status, ...extra };
+ if (unknown) return { outcome: 'unknown', status, ...extra };
+ return { outcome: 'acknowledged', status, ...extra };
+}
+
+// The persisted attempt of `token` as the store last read or wrote it. The store re-checks everything under its lease
+// when the request is sealed; this pre-check only refuses early, before any write.
+function attemptOf(store, token) {
+ const snap = store.snapshot();
+ const a = snap && snap.envelope ? snap.envelope.attempts.find((x) => x.token === token) : null;
+ if (!a || !a.rowProtocol) throw mismatch('the request names an attempt the store does not hold with a row protocol; it was not sent');
+ return a;
+}
+
+function checkRows(scope, store, c) {
+ if (!Array.isArray(c.rows) || c.rows.length === 0) throw mismatch('a row request names no row; it was not sent');
+ const a = attemptOf(store, c.token);
+ const rows = c.rows.map((r) => {
+ if (!r || typeof r.kind !== 'string' || typeof r.key !== 'string') throw mismatch('a row request names a row without a kind and key; it was not sent');
+ const id = normalizeGuid(r.id);
+ const parentId = r.parentId === null || r.parentId === undefined ? null : normalizeGuid(r.parentId);
+ const p = a.rowProtocol.rows.find((x) => x.kind === r.kind && x.key === r.key);
+ const what = `the ${r.kind} "${r.key}" of the managed ${a.family} "${a.key}"`;
+ if (!p || !id || p.id !== id) throw mismatch(`${what} is not prepared under the id ${r.id}; the request was not sent`);
+ if ((p.parentId || null) !== parentId) throw mismatch(`${what} is sent under another parent than the one prepared; the request was not sent`);
+ if (p.dispatched || scope.sent.has(`row\u0000${c.token}\u0000${id}`)) throw mismatch(`${what} was already sent once; it is not sent again`);
+ if (!Array.isArray(r.sentFields) || !r.sentFields.every((f) => typeof f === 'string' && FIELD_NAME.test(f)) || !HEX64.test(String(r.sentSha256))) {
+ throw mismatch(`${what} has no sealed projection of the request; it was not sent`);
+ }
+ if (r.answer !== undefined && !(isPlain(r.answer) && typeof r.answer.at === 'string' && FIELD_NAME.test(r.answer.at) && FIELD_NAME.test(String(r.answer.key)) && isPlain(r.answer.match) && Object.keys(r.answer.match).length > 0)) {
+ throw mismatch(`${what} names no usable place to find it in the answer; the request was not sent`);
+ }
+ return { kind: r.kind, key: r.key, id, sentFields: [...new Set(r.sentFields)].sort(), sentSha256: r.sentSha256, mode: p.mode, ...(r.answer ? { answer: r.answer } : {}) };
+ });
+ if (new Set(rows.map((r) => r.id)).size !== rows.length) throw mismatch('a row request names one row twice; it was not sent');
+ // Every identity an answer may carry is compared with the row the request prepared (answerOf), so the classifier
+ // must say which table and primary-key field that row is: without them, a body or header naming another row could
+ // not be told from one naming this row.
+ if (typeof c.expectTable !== 'string' || !FIELD_NAME.test(c.expectTable) || typeof c.expectKey !== 'string' || !FIELD_NAME.test(c.expectKey)) {
+ throw mismatch('a row request does not name the table and primary key its answer is read against; it was not sent');
+ }
+ return rows;
+}
+
+function rowHandle(scope, store, entry, c, rows) {
+ for (const r of rows) scope.sent.add(`row\u0000${c.token}\u0000${r.id}`);
+ const expectId = c.expectId === undefined ? rows[0].id : c.expectId === null ? null : normalizeGuid(c.expectId);
+ const expect = { id: expectId, table: c.expectTable, key: c.expectKey, children: rows.filter((r) => r.answer).map((r) => ({ id: r.id, ...r.answer })) };
+ const state = { dispatched: false, answered: false };
+ const fact = (a) => rows.map((r) => ({ type: 'row', token: c.token, kind: r.kind, key: r.key, id: r.id, mode: r.mode, ...a }));
+ scope.handles.push(() => (state.dispatched && !state.answered ? fact({ outcome: 'unknown', status: null, unanswered: true }) : []));
+ return {
+ dispatching() {
+ guard(scope, () => {
+ if (state.dispatched) throw mismatch('a send-once row request was about to be sent a second time; it was not sent');
+ if (scope.closed) throw mismatch('a row request was sent after its create set ended; it was not sent');
+ store.sealRowDispatch({ token: c.token, epoch: entry.epoch, rows: rows.map(({ kind, key, id, sentFields, sentSha256 }) => ({ kind, key, id, sentFields, sentSha256 })) });
+ state.dispatched = true;
+ });
+ },
+ answered(res) {
+ // One answer per send: a second one (a transport that reports twice) adds nothing the first did not say.
+ if (state.answered || scope.closed) return;
+ state.answered = true;
+ // The answer is to the whole request: a deep insert is one transaction, so every row it carried shares it.
+ scope.facts.push(...fact(answerOf(res, expect)));
+ },
+ };
+}
+
+function effectHandle(scope, store, entry, c) {
+ const id = normalizeGuid(c.id);
+ if (c.kind !== 'membership' && c.kind !== 'rule-state') throw mismatch(`a completion effect of kind ${c.kind} is not one a create set prepares; it was not sent`);
+ if (!id) throw mismatch('a completion effect names no row id; it was not sent');
+ const a = attemptOf(store, c.token);
+ const e = a.rowProtocol.effects.find((x) => x.kind === c.kind && x.id === id);
+ if (!e) throw mismatch(`the ${c.kind} of ${id} is not an effect the managed ${a.family} "${a.key}" prepared; it was not sent`);
+ const k = `effect\u0000${c.token}\u0000${c.kind}\u0000${id}`;
+ if (e.dispatched || scope.sent.has(k)) throw mismatch(`the ${c.kind} of ${id} was already sent once; it is not sent again`);
+ scope.sent.add(k);
+ const state = { dispatched: false, answered: false };
+ scope.handles.push(() => (state.dispatched && !state.answered ? [{ type: 'effect', token: c.token, kind: c.kind, id, outcome: 'unknown', status: null, unanswered: true }] : []));
+ return {
+ dispatching() {
+ guard(scope, () => {
+ if (state.dispatched) throw mismatch('a send-once completion effect was about to be sent a second time; it was not sent');
+ if (scope.closed) throw mismatch('a completion effect was sent after its create set ended; it was not sent');
+ store.markRowEffectDispatch({ token: c.token, epoch: entry.epoch, kind: c.kind, id });
+ state.dispatched = true;
+ });
+ },
+ answered(res) {
+ if (state.answered || scope.closed) return;
+ state.answered = true;
+ scope.facts.push({ type: 'effect', token: c.token, kind: c.kind, id, ...answerOf(res, null) });
+ },
+ };
+}
+
+/**
+ * The send handle of the one `$batch` a set that opted in may send (managed-create-batch.js): the Custom API change set
+ * that edits the API the set binds and adds new children, and nothing else. Before anything is written:
+ * - the request must parse as exactly that change set (framing, order, headers, fields, the bound id), with no more
+ * parts than the set's attempts prepare rows;
+ * - every constituent is classified on its own by the driver, as one prepared row of its own table, of ONE attempt of
+ * this set whose root is the bound API — kept as a bound row (an update), never created here — and carrying exactly
+ * the change and the held version token the driver prepared (constituentFault), then checked as any row request is
+ * (checkRows: prepared under that id and parent, never sent before, a sealed projection of what it carries).
+ * Then ALL constituents are sealed in ONE sealRowDispatch, counted as one possible send, and the request goes out once:
+ * the client never re-sends a claimed request, and a second dispatch is refused. The answer is read per constituent by
+ * its Content-ID (readChangesetAnswer); every constituent is acknowledged only when the whole change set is.
+ */
+function batchHandle(scope, store, req) {
+ // The set's attempts bound how many parts can belong to it: a request is never read past what it could account for.
+ const snap = store.snapshot();
+ const prepared = (snap && snap.envelope ? snap.envelope.attempts : [])
+ .filter((x) => scope.entries.has(x.token) && x.rowProtocol).reduce((n, x) => n + x.rowProtocol.rows.length, 0);
+ const parsed = parseCustomApiChangeset(req, scope.batch, { limit: Math.min(prepared, MAX_BATCH_PARTS) });
+ let token = null;
+ const admitted = parsed.constituents.map((k) => {
+ const what = `a $batch was not sent: its part ${k.contentId}`;
+ const c = scope.classify({ method: k.method, url: k.url, body: k.body, headers: { ...k.headers }, contentId: k.contentId });
+ const fault = constituentFault(c, k, parsed.boundId);
+ if (fault) throw mismatch(`${what} ${fault}`);
+ if (token === null) token = c.token;
+ if (c.token !== token) throw mismatch('a $batch was not sent: its parts belong to more than one attempt');
+ if (!scope.entries.has(c.token)) throw mismatch(`${what} names an attempt outside this create set`);
+ const [row] = checkRows(scope, store, c);
+ if (sentProjection(Object.fromEntries(row.sentFields.map((f) => [f, k.json[f]]))).sentSha256 !== row.sentSha256) {
+ throw mismatch(`${what} seals another projection than the one it carries`);
+ }
+ if (row.mode !== (k.role === 'root' ? 'update' : 'create')) throw mismatch(`${what} would ${k.role === 'root' ? 'edit an API the set creates' : 'write a child the set does not create'}`);
+ return { contentId: k.contentId, role: k.role, id: k.id, row };
+ });
+ if (new Set(admitted.map((x) => x.row.id)).size !== admitted.length) throw mismatch('a $batch was not sent: it writes one row twice');
+ const a = attemptOf(store, token);
+ const root = a.rowProtocol.rows.find((r) => r.kind === BATCH_ROLES.root.kind && r.parentId === null && r.id === parsed.boundId);
+ if (a.family !== 'customApi' || !a.root || a.root.kind !== BATCH_ROLES.root.kind || normalizeGuid(a.root.id) !== parsed.boundId || !root || root.mode !== 'update') {
+ throw mismatch('a $batch was not sent: the API it edits is not one its attempt already binds');
+ }
+ const entry = scope.entries.get(token);
+ const answerPlan = { apiBase: scope.batch.apiBase, boundId: parsed.boundId, constituents: admitted.map(({ contentId, role, id }) => ({ contentId, role, id })) };
+ for (const x of admitted) scope.sent.add(`row\u0000${token}\u0000${x.row.id}`);
+ const state = { dispatched: false, answered: false };
+ const facts = (read) => admitted.map((x, i) => ({
+ type: 'row', token, kind: x.row.kind, key: x.row.key, id: x.row.id, mode: x.row.mode, contentId: x.contentId, ...read(i),
+ }));
+ scope.handles.push(() => (state.dispatched && !state.answered ? facts(() => ({ outcome: 'unknown', status: null, unanswered: true })) : []));
+ return {
+ dispatching() {
+ guard(scope, () => {
+ if (state.dispatched) throw mismatch('a send-once $batch was about to be sent a second time; it was not sent');
+ if (scope.closed) throw mismatch('a $batch was sent after its create set ended; it was not sent');
+ store.sealRowDispatch({ token, epoch: entry.epoch, rows: admitted.map(({ row: { kind, key, id, sentFields, sentSha256 } }) => ({ kind, key, id, sentFields, sentSha256 })) });
+ state.dispatched = true;
+ });
+ },
+ answered(res) {
+ if (state.answered || scope.closed) return;
+ state.answered = true;
+ const read = readChangesetAnswer(res, answerPlan);
+ scope.facts.push(...facts((i) => ({ ...read.parts[i], batchStatus: read.batchStatus, ...(read.failure ? { changesetFailure: read.failure } : {}) })));
+ },
+ };
+}
+
+// Run `fn`; a throw is recorded as the scope's local failure before it propagates (into the SDK, which may swallow it).
+function guard(scope, fn) {
+ try {
+ return fn();
+ } catch (e) {
+ latch(scope, e);
+ throw e;
+ }
+}
+// Keep `e` as one of the scope's local failures; the first one kept is the one the scope answers (localError).
+function latch(scope, e) {
+ if (!scope.errors.includes(e)) scope.errors.push(e);
+}
+
+/**
+ * The deferred gate of one invocation: { screen(req), bind(store), boundTo(store) }. Inert outside a create-set scope;
+ * inside one, unbound or bound to another store, every mutation is refused unsent (managed-create-request-mismatch).
+ * Bound at most once, to the invocation's one store: a second, different store is a wiring fault and is refused.
+ */
+function createDeferredManagedCreateGate() {
+ let store = null;
+ return {
+ screen({ method, url, body, headers } = {}) {
+ const scope = als.getStore();
+ if (!scope) return null;
+ const m = String(method || 'GET').toUpperCase();
+ if (isRead(m)) return null;
+ return guard(scope, () => {
+ if (scope.closed) throw mismatch(`a ${m} was not sent: its create set has ended`);
+ if (scope.errors.length) throw mismatch(`a ${m} was not sent: an earlier request of this create set failed locally, and nothing further is sent`);
+ if (!store) throw mismatch(`a ${m} was not sent: the managed create gate is not bound to the invocation's binding store`);
+ if (scope.store && scope.store !== store) throw mismatch(`a ${m} was not sent: the create set belongs to another binding store than the gate's`);
+ if (m === 'DELETE') throw mismatch(`a DELETE was not sent: a protected ${scope.label} never removes a row`, scope.deleteCode);
+ if (m === 'POST' && apiPath(url) === '$batch') {
+ if (!scope.batch) throw mismatch(`a $batch was not sent: a protected ${scope.label} sends each change on its own`);
+ return batchHandle(scope, store, { url, body, headers });
+ }
+ const c = scope.classify({ method: m, url, body, headers });
+ if (!c) throw mismatch(`a ${m} was not sent: it is not a change the protected ${scope.label} prepared`);
+ const entry = scope.entries.get(c.token);
+ if (!entry) throw mismatch(`a ${m} was not sent: it names an attempt outside this create set`);
+ if (c.type === 'rows') return rowHandle(scope, store, entry, c, checkRows(scope, store, c));
+ if (c.type === 'effect') return effectHandle(scope, store, entry, c);
+ throw mismatch(`a ${m} was not sent: the classifier answered an unknown request type`);
+ });
+ },
+ bind(next) {
+ if (!next || typeof next.snapshot !== 'function' || typeof next.sealRowDispatch !== 'function') throw new TypeError('the managed create gate binds to a managed binding store');
+ if (store === next) return;
+ if (store) throw new Error('the managed create gate is already bound to another managed binding store');
+ store = next;
+ },
+ boundTo(candidate) {
+ return Boolean(store) && store === candidate;
+ },
+ };
+}
+
+/**
+ * Run `fn` (the SDK operation of a protected create set) inside its request scope:
+ * set = {
+ * store, the store the gate must be bound to (checked at each mutation);
+ * entries: [{ token, epoch }], what markAttemptSetSending answered (the attempts this scope may send under);
+ * classify(req) -> descriptor, the driver's classifier of one mutation { method, url, body, headers }:
+ * { type: 'rows', token, rows: [{ kind, key, id, parentId, sentFields, sentSha256, answer? }], expectTable, expectKey, expectId? }
+ * one request carrying those rows (a deep insert carries a root and its children). `expectTable` is the
+ * entity set the request's own row is answered under (customapis) and `expectKey` its primary-key field
+ * (customapiid); `expectId` is the id an answer must name (default: the first row's; null: none). A child
+ * the body returns names where it is found: answer: { at: '<navigation property>', key: '<its primary key>',
+ * match: { <field>: <value>, ... } }. See answerOf;
+ * { type: 'effect', token, kind: 'membership' | 'rule-state', id }
+ * null for anything else (refused);
+ * deleteCode?, the code a DELETE is refused with (default managed-create-request-mismatch);
+ * label?, how messages name the set (default 'create set');
+ * batch?, { apiBase, solution }: admit the one Custom API change set managed-create-batch.js
+ * reads, sent through the SDK under that API base and solution header (batchConfig).
+ * Each constituent is classified on its own, as { type: 'rows', token, expectTable,
+ * expectKey, rows: [one row], prepared, ifMatch? } (constituentFault). Without it every
+ * `$batch` is refused;
+ * }
+ * Answers { value, error, localError, facts } and never throws for `fn`: `error` is what `fn` threw (or null), `localError`
+ * the first local refusal or store failure inside the scope (or null) — the one to surface when set — and `facts` the
+ * in-memory answers [{ type: 'row', token, kind, key, id, mode, outcome, status, answeredId? } | { type: 'effect', token,
+ * kind, id, outcome, status }]; a request dispatched and not answered when `fn` settled is an `unknown` fact with
+ * `unanswered: true`. A change set's row facts also carry their `contentId`, the outer `batchStatus` and, when the
+ * service reported one constituent failed, `changesetFailure` (a diagnostic only). The scope closes when `fn` settles: a
+ * request it left running is refused after that, and an answer that arrives after it is not read.
+ */
+async function runWithManagedCreateSet(set, fn) {
+ if (!set || typeof set.classify !== 'function' || !Array.isArray(set.entries) || set.entries.length === 0) throw new TypeError('runWithManagedCreateSet needs the set\'s entries and its classifier');
+ if (typeof fn !== 'function') throw new TypeError('runWithManagedCreateSet needs the operation to run');
+ const batch = set.batch === undefined || set.batch === null ? null : batchConfig(set.batch);
+ const entries = new Map();
+ for (const e of set.entries) {
+ if (!e || typeof e.token !== 'string' || entries.has(e.token)) throw new TypeError('runWithManagedCreateSet entries are distinct { token, epoch }');
+ entries.set(e.token, { token: e.token, epoch: e.epoch === undefined ? null : e.epoch });
+ }
+ const scope = {
+ store: set.store || null, entries, classify: set.classify, deleteCode: set.deleteCode || MISMATCH, label: set.label || 'create set', batch,
+ sent: new Set(), facts: [], errors: [], handles: [], closed: false,
+ };
+ let value;
+ let error = null;
+ try {
+ value = await als.run(scope, fn);
+ } catch (e) {
+ error = e;
+ }
+ scope.closed = true;
+ // A request that was dispatched and never answered before the operation settled (the SDK did not await it, or its
+ // answer was lost) may still be applied: it is an unknown fact, never silence a later check could read as success.
+ for (const pending of scope.handles) scope.facts.push(...pending());
+ return { value, error, localError: scope.errors[0] || null, facts: scope.facts.slice() };
+}
+
+/** Is the caller inside a protected create-set scope? */
+function inManagedCreateSet() {
+ return Boolean(als.getStore());
+}
+
+/**
+ * One gate for the client's one slot, from several (null entries are skipped). Every gate is asked; a throw from any
+ * refuses the request unsent; a request two gates both claim (two send handles) is refused unsent — it would have two
+ * owners; otherwise the one handle, or null. A request no gate claims is sent exactly as before.
+ * Inside a protected create-set scope the WHOLE composed boundary is latched: whichever gate throws, in whatever order
+ * the gates were composed (the workflow effect gate's refusal included), and a claimed handle's `dispatching()` refusal,
+ * the first error is kept as the scope's local failure before it is rethrown. The SDK catches what the client throws and
+ * may report a result of its own; without the latch, a request refused here could leave a scope that reads as saved.
+ * Outside a scope nothing is latched and every gate and handle is used exactly as it was.
+ */
+function composeWriteGates(...gates) {
+ const list = gates.filter(Boolean);
+ for (const g of list) if (typeof g.screen !== 'function') throw new TypeError('composeWriteGates takes gates with a screen()');
+ const screenAll = (req) => {
+ let handle = null;
+ for (const g of list) {
+ const h = g.screen(req);
+ if (!h) continue;
+ if (handle) {
+ const m = String((req && req.method) || 'GET').toUpperCase();
+ throw mismatch(`a ${m} was not sent: two write gates both claim it`);
+ }
+ handle = h;
+ }
+ return handle;
+ };
+ return {
+ screen(req) {
+ const scope = als.getStore();
+ if (!scope) return screenAll(req);
+ let handle;
+ try {
+ handle = screenAll(req);
+ } catch (e) {
+ latch(scope, e);
+ throw e;
+ }
+ if (!handle) return handle;
+ const latched = Object.create(handle);
+ latched.dispatching = (...args) => {
+ try {
+ return handle.dispatching(...args);
+ } catch (e) {
+ latch(scope, e);
+ throw e;
+ }
+ };
+ return latched;
+ },
+ };
+}
+
+module.exports = {
+ MISMATCH,
+ createDeferredManagedCreateGate,
+ runWithManagedCreateSet,
+ composeWriteGates,
+ inManagedCreateSet,
+ sentProjection,
+ answerOf,
+};
diff --git a/plugins/model-apps/scripts/lib/phase-diff.js b/plugins/model-apps/scripts/lib/phase-diff.js
index e050c9820..9cbeb3d47 100644
--- a/plugins/model-apps/scripts/lib/phase-diff.js
+++ b/plugins/model-apps/scripts/lib/phase-diff.js
@@ -21,7 +21,15 @@ const PHASE_SLICES = {
// data-model owns the whole schema; a change here can ripple into everything downstream (views,
// charts, forms reference columns; app-shell references entities), so callers treat a data-model
// change as "recommend a full build", not "run only data-model".
- 'data-model': (s) => ({ entities: s.entities, relationships: s.relationships, globalChoices: s.globalChoices }),
+ // The configuration kinds (lib/configuration-artifacts.js FIELDS) are written in the solution and data-model phases, and the protected
+ // opt-in decides how. They were missing here, so a spec whose only change was one of them diffed as "nothing changed" and
+ // `--changed-only` applied nothing; as part of this slice a change to any of them is a full build (FULL_BUILD_PHASES). An absent field
+ // compares as null on both sides, so a spec that declares none of them compares exactly as it did.
+ 'data-model': (s) => ({
+ entities: s.entities, relationships: s.relationships, globalChoices: s.globalChoices,
+ configurationIdentity: s.configurationIdentity, environmentVariables: s.environmentVariables, connectionReferences: s.connectionReferences,
+ customApis: s.customApis, duplicateDetectionRules: s.duplicateDetectionRules,
+ }),
'sample-data': (s) => s.sampleData,
'web-resources': (s) => s.webResources,
views: (s) => s.views,
diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.js
index 3777f0a64..355bcbb83 100644
--- a/plugins/model-apps/scripts/lib/sdk-build.js
+++ b/plugins/model-apps/scripts/lib/sdk-build.js
@@ -173,7 +173,7 @@ const { createFeatureSettlement, refusal: featureRefusal, isAuthorized, approval
const { createPassthroughCreates } = require('./creates-passthrough.js');
const { isDeclaredView, declaredViewKey, planViewReconcile, applyViewReconcile } = require('./view-reconcile.js');
const { isDeclaredChart, declaredChartKey, planChartReconcile, applyChartReconcile } = require('./chart-reconcile.js');
-const { openManagedContext, isStoreEnvironment, attemptProvenUnsent } = require('./managed-bindings.js');
+const { openManagedContext, isStoreEnvironment, attemptProvenUnsent, discoverManagedStore, ROW_FAMILIES } = require('./managed-bindings.js');
const { isManagedEntity, planCommandReconcile, applyCommandReconcile } = require('./command-reconcile.js');
const { planQuickFind, applyQuickFind } = require('./quick-find.js');
const { HTTP_SEND_HISTORY } = require('./sdk-http-client.js');
@@ -181,7 +181,7 @@ const { HTTP_SEND_HISTORY } = require('./sdk-http-client.js');
// the helper plans, applies and reads them back; the runtime closes over what only the build has (its create port, BuildHalt and
// retry policy, the --authorize keys) so this file calls three methods and keeps no configuration state of its own.
const { usesConfiguration, hasConfigurationDefinitions, configurationPlanItems } = require('./configuration-artifacts.js');
-const { createConfigurationRuntime } = require('./configuration-build.js');
+const { createConfigurationRuntime, sweepPendingConfiguration } = require('./configuration-build.js');
// Declared forms (forms[].reconcile "declared", lib/form-layout-reconcile.js) are dispatched only while their enable flag is on
// (lib/declared-features.js). With it off, no form is declared here — validation refuses `reconcile` on a form — so every form
// takes the build's own path and every spec sends the requests it always sent.
@@ -3404,6 +3404,46 @@ function openBuildBindingGroups(spec, { apply, env, workspaceDir, appDir, barrie
}
}
+// Is protected configuration (`configurationIdentity: "stable-v1"`, lib/configuration-protected.js) in play for this apply? Yes when the
+// App Spec opts in, and also when the opt-in is gone but the workspace's binding store still holds state for a configuration family
+// (ROW_FAMILIES: a committed group, a pending attempt, or a group it cannot use): removing the opt-in keeps what the store owes, so the
+// build must still run the store's debt sweep and its opt-in-removed stop (create-identity-opt-in-required). build-model-app.js asks this
+// before it makes the SDK, to decide whether to make the deferred managed-create gate at all.
+// The store read is discoverManagedStore: the same read-only, local-only discovery openBuildBindingGroups runs, in a module the build
+// has already loaded. It sends no request, creates no file and loads no protected module, so an App Spec without the opt-in whose
+// store holds no configuration row (or that has no store) builds exactly as before. A store it cannot read answers yes (fail closed):
+// the build then stops on that store before any write anyway (openBuildBindingGroups, managed-binding-store-unreadable).
+function protectedConfigurationInPlay(spec, { apply, env, workspaceDir, appDir } = {}) {
+ if (!apply || !spec) return false;
+ if (spec.configurationIdentity === 'stable-v1') return true;
+ const sol = spec.solution;
+ if (!spec.app || !sol || !sol.uniqueName || !isStoreEnvironment(env)) return false;
+ try {
+ const found = discoverManagedStore({ workspaceDir: applyWorkspaceOf({ workspaceDir, appDir }), environment: env, appUniqueName: appUniqueName(spec), solutionUniqueName: sol.uniqueName });
+ return !found.absent && found.loaded.units().some((u) => ROW_FAMILIES.includes(u.family));
+ } catch {
+ return true;
+ }
+}
+
+// The protected configuration hookup of one invocation (lib/configuration-protected.js createProtectedConfiguration), made the first time
+// an attempt needs it and kept by its gate: every attempt of a whole-build retry (build-model-app.js) shares the one managed create
+// context, so an answer one attempt received is still known to the next. Keyed by the gate, which the CLI makes once per invocation.
+const protectedHookups = new WeakMap();
+function protectedConfigurationFor(gate, store, { env, approvals } = {}) {
+ const made = protectedHookups.get(gate);
+ if (made && made.store === store) return made;
+ const { createManagedCreateContext } = require('./managed-create-context.js');
+ const { NOT_FOUND_CODE } = require('./configuration-create-bindings.js');
+ const { createProtectedConfiguration } = require('./configuration-protected.js');
+ // The maker's `--authorize adopt:<kind>:...` row approvals (build-model-app.js authorizationKeys), exactly as the preflight printed them.
+ const ctx = createManagedCreateContext({ store, approvals: approvals ? [...approvals] : [], notFoundCode: NOT_FOUND_CODE });
+ // The API root the SDK prefixes every request with (the bundle uses v9.0): a Custom API change set is admitted only under it.
+ const hookup = createProtectedConfiguration({ store, gate, ctx, apiBase: `${new URL(String(env)).origin}/api/data/v9.0` });
+ protectedHookups.set(gate, hookup);
+ return hookup;
+}
+
// The entry every caller enters by. An APPLY holds the app's build lease for the whole of it (lib/app-operation-lease.js): one taken here when the
// caller holds none, or the caller's own (`opts.buildLease`, which buildModelApp hands to each attempt), borrowed and left to the caller to let go. A
// 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,
@@ -3831,6 +3871,18 @@ async function runSdkBuildPhases(spec, opts, owed) {
|| (workflowStore.snapshot().envelope.workflowEffects || []).length > 0)) {
opts.workflowEffectGate.bind(workflowStore);
}
+ // Protected configuration's deferred managed-create gate (lib/managed-create-transport.js), which build-model-app.js makes only while
+ // protected configuration is in play (protectedConfigurationInPlay) and installs on the shared HTTP client with the workflow gate.
+ // It is bound here, once, to the store every attempt shares, and the configuration hookup is made over both before the build's first
+ // service change below: its debt sweep, its whole-plan preflight and its opt-in-removed stop all run ahead of every write, whatever
+ // phases or changed-only selection this run has. Without a store (no solution, or a target no store is kept for) nothing is bound and
+ // no hookup is made: under the opt-in the configuration preflight then stops the build before any write (create-identity-unverified).
+ // A hookup the caller handed over (opts.protectedConfiguration) is used as it is.
+ let configurationOpts = opts;
+ if (opts.managedCreateGate && workflowStore && !opts.protectedConfiguration) {
+ opts.managedCreateGate.bind(workflowStore);
+ configurationOpts = { ...opts, protectedConfiguration: protectedConfigurationFor(opts.managedCreateGate, workflowStore, { env: opts.env, approvals: opts.configurationApprovals }) };
+ }
// A declared artifact that did not settle stops the build. Its result's own findings decide — never the SDK error
// behind them: rethrown, a 5xx answer would make the runner judge an unsettled create as transient and retry it, and a
// create that may have stored a row must be inspected first. RETRY.NEVER marks the halt `transient: false`, which
@@ -4158,7 +4210,13 @@ async function runSdkBuildPhases(spec, opts, owed) {
};
// The configuration kinds' runtime (lib/configuration-build.js), or null for a spec that uses none of them: then no step below runs and
// nothing is read for them. Built before the first write so a spec that declares an item twice stops here, having written nothing.
- const configurationRun = usesConfiguration(spec) ? createConfigurationRuntime({ spec, sdk, provision, opts, appUniqueName: appUniqueName(spec) }) : null;
+ const configurationRun = usesConfiguration(spec) ? createConfigurationRuntime({ spec, sdk, provision, opts: configurationOpts, appUniqueName: appUniqueName(spec) }) : null;
+ // Protected configuration (configurationIdentity "stable-v1") is checked whole and read-only here, before the first write below: an edit
+ // the protected path cannot make stops the build with nothing sent (lib/configuration-build.js preflight; a no-op without the opt-in).
+ // The binding store's configuration debt is read first either way: an App Spec that dropped every configuration item (no runtime)
+ // 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);
// 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
@@ -10915,4 +10973,4 @@ async function runSdkBuildPhases(spec, opts, owed) {
return result;
}
-module.exports = { runSdkBuild, openBuildBindingGroups, 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, 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/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.js
index fb376ac20..4bc9c97b2 100644
--- a/plugins/model-apps/scripts/lib/verify-spec.js
+++ b/plugins/model-apps/scripts/lib/verify-spec.js
@@ -2349,17 +2349,19 @@ async function verifySpec(spec, read, opts = {}) {
// The configuration kinds: one check per declared item and aspect (definition, binding, value, implementation, publication, version),
// in declaration order. A Custom API whose implementation is not proven (no plug-in type: a scaffold) is reported as unverified, not as
- // missing — the API is deployed; whether it runs is not something a read can prove. A reader without the getter says so.
+ // missing — the API is deployed; whether it runs is not something a read can prove. A reader without the getter says so. Under
+ // `configurationIdentity: "stable-v1"` the getter reads each item at the id the workspace's binding store holds (`opts.managedManifest`),
+ // and an item whose attempt is still pending (managed-settlement-pending) proves nothing yet: it is unverified, never a pass.
if (require('./configuration-artifacts.js').usesConfiguration(spec)) {
plan.section(async ({ add, unverified }) => {
if (!read || typeof read.configuration !== 'function') {
unverified.push('configuration (this reader cannot read configuration items)');
return;
}
- for (const c of await read.configuration(spec, opts.configurationBindings)) {
+ for (const c of await read.configuration(spec, opts.configurationBindings, opts.managedManifest)) {
const name = `${c.kind} ${c.key}: ${c.name}`;
if (c.ok) add('configuration', name, true);
- else if (c.code === 'CUSTOM_API_IMPLEMENTATION_UNPROVEN') unverified.push(`configuration:${name} (${c.code})`);
+ else if (c.code === 'CUSTOM_API_IMPLEMENTATION_UNPROVEN' || c.code === 'managed-settlement-pending') unverified.push(`configuration:${name} (${c.code})`);
else add('configuration', name, false, `${c.code}${Array.isArray(c.fields) && c.fields.length ? ` (${c.fields.join(', ')})` : ''}`);
}
});
diff --git a/plugins/model-apps/scripts/lib/workflow-effect-context.js b/plugins/model-apps/scripts/lib/workflow-effect-context.js
index cc9de3d04..22a81cb2b 100644
--- a/plugins/model-apps/scripts/lib/workflow-effect-context.js
+++ b/plugins/model-apps/scripts/lib/workflow-effect-context.js
@@ -337,4 +337,6 @@ module.exports = {
classifyWorkflowRequest: classify,
batchParts,
parseBatch,
+ apiPath,
+ headerValue,
};
diff --git a/plugins/model-apps/scripts/tests/app-spec-keys.test.js b/plugins/model-apps/scripts/tests/app-spec-keys.test.js
index c2349f789..f0bcc603e 100644
--- a/plugins/model-apps/scripts/tests/app-spec-keys.test.js
+++ b/plugins/model-apps/scripts/tests/app-spec-keys.test.js
@@ -907,36 +907,87 @@ test('minimumPluginVersion refuses a spec that needs a newer plugin than the one
}
});
-// #799: a `views[]` key the build does not read used to validate clean and be dropped, so a view written with `filter` was built without its filter.
+// #799, #827: a `views[]` key the build does not read used to validate clean and be dropped, so a view written with `filter` was built without
+// its filter. It is now an error under every profile that builds or plans a build (and a warning in the same words where a spec is only read).
const withViews = (views) => Object.assign(base(), { views });
-const viewWarnings = (views, opts = { profile: 'plan' }) => validateAppSpec(withViews(views), opts).warnings.filter((w) => /unknown key/.test(w));
+const viewKeyErrors = (views, opts = { profile: 'plan' }) => validateAppSpec(withViews(views), opts).errors.filter((e) => /unknown key/.test(e));
+
+test('#827: a view written with `filter` is refused, naming `filters`, and is no warning as well', () => {
+ const r = validateAppSpec(withViews([{ entity: 'contoso_order', name: 'High Priority', filter: [{ attr: 'contoso_priority', op: 'eq', value: 5 }] }]), { profile: 'plan' });
+ assert.strictEqual(r.ok, false, 'a view that would be built without its filter must fail validation');
+ const e = r.errors.filter((x) => /unknown key 'filter'/.test(x));
+ assert.strictEqual(e.length, 1, `expected one error for 'filter'; got ${JSON.stringify(r.errors)}`);
+ assert.match(e[0], /view 'High Priority'/);
+ assert.match(e[0], /did you mean 'filters'\?/);
+ assert.match(e[0], /refused rather than built without it/);
+ assert.match(e[0], /allowed: entity, name, description, columns, sort, filters,/);
+ assert.deepStrictEqual(r.warnings.filter((x) => /unknown key/.test(x)), []);
+});
+
+test('#827: a filter item written with `column` and `operator` is refused once, naming `attr` and `op`', () => {
+ const errors = viewKeyErrors([{ entity: 'contoso_order', name: 'High Priority', filters: [{ column: 'contoso_priority', operator: 'eq', value: 5 }] }]);
+ const column = errors.find((x) => /unknown key 'column'/.test(x));
+ const operator = errors.find((x) => /unknown key 'operator'/.test(x));
+ assert.ok(column && /filters\[0\]/.test(column) && /did you mean 'attr'\?/.test(column), `got ${JSON.stringify(errors)}`);
+ assert.ok(operator && /did you mean 'op'\?/.test(operator), `got ${JSON.stringify(errors)}`);
+ const all = validateAppSpec(withViews([{ entity: 'contoso_order', name: 'High Priority', filters: [{ column: 'contoso_priority', operator: 'eq', value: 5 }] }]), { profile: 'plan' }).errors;
+ assert.strictEqual(all.filter((x) => /filters\[0\]\.attr must be a non-empty column name/.test(x)).length, 1, `the missing-attr error is reported once, as before: ${JSON.stringify(all)}`);
+});
+
+test('#827: an unknown key on a filter of a declared join is refused too', () => {
+ const errors = viewKeyErrors([{ entity: 'contoso_order', name: 'Joined', reconcile: 'declared', columns: ['contoso_name'],
+ linkEntities: [{ name: 'contact', from: 'contactid', to: 'primarycontactid', alias: 'c', filters: [{ attr: 'lastname', operator: 'eq', value: 'Smith' }] }] }]);
+ assert.strictEqual(errors.length, 1, JSON.stringify(errors));
+ assert.match(errors[0], /linkEntities\[0\]\.filters\[0\]: unknown key 'operator' — did you mean 'op'\?/);
+});
+
+test('#827: the structural profile and `viewKeys: "warn"` keep an app built from such a spec readable: the same words, as a warning, and nothing else moves', () => {
+ const views = [{ entity: 'contoso_order', name: 'Red orders', filter: [{ attr: 'contoso_priority', op: 'eq', value: 5 }] }];
+ const strict = validateAppSpec(withViews(views), { profile: 'deploy' });
+ assert.strictEqual(strict.errors.filter((x) => /unknown key 'filter'/.test(x)).length, 1, JSON.stringify(strict.errors));
+ for (const options of [{ profile: 'structural' }, { profile: 'deploy', viewKeys: 'warn' }]) {
+ const r = validateAppSpec(withViews(views), options);
+ const label = JSON.stringify(options);
+ assert.deepStrictEqual(r.errors.filter((x) => /unknown key/.test(x)), [], label);
+ assert.deepStrictEqual(r.warnings.filter((x) => /unknown key 'filter'/.test(x)), strict.errors.filter((x) => /unknown key 'filter'/.test(x)), label);
+ }
+ for (const options of [{ viewKeys: true }, { viewKeys: 'WARN' }, { viewKeys: 'error' }, { fieldOptionKeys: 'warn' }, { columnValues: 'warn' }]) {
+ const r = validateAppSpec(withViews(views), { profile: 'deploy', ...options });
+ assert.strictEqual(r.errors.filter((x) => /unknown key 'filter'/.test(x)).length, 1, JSON.stringify(options));
+ }
+});
-test('#799: a view written with `filter` warns and names `filters`; the spec still validates', () => {
- const r = validateAppSpec(withViews([{ entity: 'contoso_order', name: 'High Priority', filter: [{ column: 'contoso_priority', operator: 'eq', value: 5 }] }]), { profile: 'plan' });
- assert.strictEqual(r.ok, true, `a warning must not fail a spec that validated before; got ${JSON.stringify(r.errors)}`);
- const w = r.warnings.filter((x) => /unknown key 'filter'/.test(x));
- assert.strictEqual(w.length, 1, `expected one warning for 'filter'; got ${JSON.stringify(r.warnings)}`);
- assert.match(w[0], /view 'High Priority'/);
- assert.match(w[0], /did you mean 'filters'\?/);
+test('#827: other unknown keys stay the warnings they were; a key of a form entry or a table is not touched', () => {
+ const r = validateAppSpec(withViews([{ entity: 'contoso_order', name: 'Mine', viewId: '11111111-1111-1111-1111-111111111111', linkEntities: [] }]), { profile: 'plan' });
+ assert.deepStrictEqual(r.errors.filter((x) => /view 'Mine'/.test(x)), [], 'viewId on a view that is not declared is still only advice');
+ assert.ok(r.warnings.some((x) => /view 'Mine': viewId and linkEntities are read only on a view with reconcile: "declared"/.test(x)), JSON.stringify(r.warnings));
});
-test('#799: a filter item written with `column` and `operator` warns and names `attr` and `op`', () => {
- const warnings = viewWarnings([{ entity: 'contoso_order', name: 'High Priority', filters: [{ column: 'contoso_priority', operator: 'eq', value: 5 }] }]);
- const column = warnings.find((x) => /unknown key 'column'/.test(x));
- const operator = warnings.find((x) => /unknown key 'operator'/.test(x));
- assert.ok(column && /filters\[0\]/.test(column) && /did you mean 'attr'\?/.test(column), `got ${JSON.stringify(warnings)}`);
- assert.ok(operator && /did you mean 'op'\?/.test(operator), `got ${JSON.stringify(warnings)}`);
+test('#827: a view key that is one edit from a supported one is matched; `type`, which older docs showed, is still accepted silently', () => {
+ const errors = viewKeyErrors([{ entity: 'contoso_order', name: 'Mine', column: ['contoso_name'], activeonly: false, type: 'main' }]);
+ assert.ok(errors.some((x) => /unknown key 'column'.*did you mean 'columns'\?/.test(x)), JSON.stringify(errors));
+ assert.ok(errors.some((x) => /unknown key 'activeonly'.*did you mean 'activeOnly'\?/.test(x)), JSON.stringify(errors));
+ assert.deepStrictEqual(errors.filter((x) => /'type'/.test(x)), [], 'a spec written from the older docs must not start to fail');
+ const typeOnly = validateAppSpec(withViews([{ entity: 'contoso_order', name: 'Mine', type: 'main' }]), { profile: 'plan' });
+ assert.strictEqual(typeOnly.ok, true, JSON.stringify(typeOnly.errors));
+ assert.deepStrictEqual(typeOnly.warnings.filter((x) => /unknown key/.test(x)), []);
+});
+
+test('#827: a view written with `where`, `conditions`, `orderBy` or `table` is refused, with the key to write instead', () => {
+ const expected = { where: 'filters', conditions: 'filters', orderBy: 'sort', table: 'entity' };
+ for (const [key, meant] of Object.entries(expected)) {
+ const errors = viewKeyErrors([{ entity: 'contoso_order', name: 'Mine', [key]: [] }]);
+ assert.strictEqual(errors.length, 1, `${key}: ${JSON.stringify(errors)}`);
+ assert.ok(errors[0].includes(`unknown key '${key}' — did you mean '${meant}'?`), errors[0]);
+ }
});
-test('#799: a view key that is one edit from a supported one is matched; `type`, which older docs showed, is still accepted silently', () => {
- const warnings = viewWarnings([{ entity: 'contoso_order', name: 'Mine', column: ['contoso_name'], activeonly: false, type: 'main' }]);
- assert.ok(warnings.some((x) => /unknown key 'column'.*did you mean 'columns'\?/.test(x)), JSON.stringify(warnings));
- assert.ok(warnings.some((x) => /unknown key 'activeonly'.*did you mean 'activeOnly'\?/.test(x)), JSON.stringify(warnings));
- assert.deepStrictEqual(warnings.filter((x) => /'type'/.test(x)), [], 'a spec written from the older docs must not start to warn');
- assert.deepStrictEqual(viewWarnings([{ entity: 'contoso_order', name: 'Mine', type: 'main' }]), []);
+test('#827: no script but the verify CLI passes the view key downgrade', () => {
+ const { scriptsMatching } = require('./helpers/production-scripts.js');
+ assert.deepStrictEqual(scriptsMatching(/viewKeys\s*:\s*['"]warn['"]/), ['verify-model-app.js']);
});
-test('#799: every key the build reads on a view and its filters stays warning-free', () => {
+test('#799: every key the build reads on a view and its filters stays error- and warning-free', () => {
const views = [
{ entity: 'contoso_order', name: 'Plain', description: 'd', columns: ['contoso_name'], sort: [{ attr: 'contoso_name', dir: 'asc' }], activeOnly: false,
filters: [{ attr: 'contoso_priority', op: 'eq', value: 5 }, { attr: 'contoso_priority', op: 'not-in', values: [1, 2] }, { attr: 'ownerid', op: 'eq-userid' }] },
@@ -951,10 +1002,11 @@ test('#799: every key the build reads on a view and its filters stays warning-fr
}
});
-test('#799: an unknown key on a join filter warns; a hint key that collides with Object.prototype leaks nothing; non-object filters do not crash', () => {
- const warnings = viewWarnings([{ entity: 'contoso_order', name: 'Joined', reconcile: 'declared', columns: ['contoso_name'], constructor: 1, toString: 2,
+test('#799: an unknown key on a join filter is reported; a hint key that collides with Object.prototype leaks nothing; non-object filters do not crash or report twice', () => {
+ const errors = viewKeyErrors([{ entity: 'contoso_order', name: 'Joined', reconcile: 'declared', columns: ['contoso_name'], constructor: 1, toString: 2,
linkEntities: [{ name: 'contact', from: 'contactid', to: 'primarycontactid', alias: 'c', filters: [{ column: 'lastname', op: 'eq', value: 'Smith' }] }] }]);
- assert.ok(warnings.some((x) => /linkEntities\[0\]\.filters\[0\]: unknown key 'column'/.test(x)), JSON.stringify(warnings));
- assert.ok(warnings.every((x) => !/native code/.test(x)), JSON.stringify(warnings));
+ assert.ok(errors.some((x) => /linkEntities\[0\]\.filters\[0\]: unknown key 'column'/.test(x)), JSON.stringify(errors));
+ assert.ok(errors.every((x) => !/native code/.test(x)), JSON.stringify(errors));
assert.doesNotThrow(() => validateAppSpec(withViews([{ entity: 'contoso_order', name: 'Odd', filters: ['x', null, 3] }]), { profile: 'plan' }));
+ assert.deepStrictEqual(viewKeyErrors([{ entity: 'contoso_order', name: 'Odd', filters: ['x', null, 3] }]), [], 'a non-object filter is the shape checks\' to report');
});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/build-model-app.test.js b/plugins/model-apps/scripts/tests/build-model-app.test.js
index 9e212f753..cf24a5c06 100644
--- a/plugins/model-apps/scripts/tests/build-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/build-model-app.test.js
@@ -76,6 +76,50 @@ test('rejects an invalid spec before any build', async () => {
assert.strictEqual(calls.length, 0, 'no SDK writes on a bad spec');
});
+// An SDK double that counts EVERY method the build calls, not only the ones mockSdk() logs: several writes (createPublisher, pushArtifact, updateRecord,
+// addSolutionComponent, publishArtifact) are not in its `calls`, so a count of `calls` alone would miss a build that wrote before it validated.
+function countingSdk() {
+ const { sdk } = mockSdk();
+ const touched = [];
+ return { sdk: new Proxy(sdk, { get: (target, name) => (typeof target[name] === 'function' ? (...args) => { touched.push(String(name)); return target[name](...args); } : target[name]) }), touched };
+}
+
+test('a view written with `filter` is refused on load, before any SDK call, while the same view written with `filters` is built', async () => {
+ const withKey = (key) => { const s = jclone(desk); s.views.find((v) => v.name === 'Active Tickets')[key] = [{ attr: 'new_status', op: 'eq', value: 1 }]; return s; };
+ const refused = countingSdk();
+ const r = await buildModelApp(withKey('filter'), { apply: true, env: 'https://x' }, { sdk: refused.sdk });
+ assert.strictEqual(r.ok, false);
+ assert.ok(r.errors.some((e) => /^view 'Active Tickets': unknown key 'filter' — did you mean 'filters'\?/.test(e)), JSON.stringify(r.errors));
+ assert.deepStrictEqual(refused.touched, [], 'no SDK method is called on a spec whose view would be built without its filter');
+ const built = countingSdk();
+ const ok = await buildModelApp(withKey('filters'), { apply: true, env: 'https://x' }, { sdk: built.sdk });
+ assert.strictEqual(ok.ok, true, JSON.stringify(ok.errors));
+ assert.ok(built.touched.length > 0, 'the control spec is built');
+});
+
+// The structural profile reads a spec to tear it down or preview it and lets an unknown view key through as a warning; a build that applied under it would
+// write the view without that part. So an apply refuses it, with no SDK call, whatever the spec holds — and the same spec under it is still accepted to read.
+test('an apply asked to validate under the structural profile is refused before any SDK call, on a spec with a typo and on one without', async () => {
+ const withKey = (key) => { const s = jclone(desk); s.views.find((v) => v.name === 'Active Tickets')[key] = [{ attr: 'new_status', op: 'eq', value: 1 }]; return s; };
+ for (const [label, spec] of [['with `filter`', withKey('filter')], ['with `filters`', withKey('filters')]]) {
+ const refused = countingSdk();
+ const r = await buildModelApp(spec, { apply: true, env: 'https://x', profile: 'structural' }, { sdk: refused.sdk });
+ assert.strictEqual(r.ok, false, label);
+ assert.ok(r.errors.some((e) => /cannot validate under the 'structural' profile/.test(e)), `${label}: ${JSON.stringify(r.errors)}`);
+ assert.deepStrictEqual(refused.touched, [], `${label}: no SDK method is called`);
+ }
+ const structural = validateAppSpec(withKey('filter'), { profile: 'structural' });
+ assert.strictEqual(structural.ok, true, 'a spec read to tear it down or preview it is still accepted');
+ assert.ok(structural.warnings.some((w) => /unknown key 'filter'/.test(w)));
+ for (const profile of ['plan', 'deploy']) {
+ const refused = countingSdk();
+ const r = await buildModelApp(withKey('filter'), { apply: true, env: 'https://x', profile }, { sdk: refused.sdk });
+ assert.strictEqual(r.ok, false, profile);
+ assert.ok(r.errors.some((e) => /unknown key 'filter'/.test(e)), `${profile}: ${JSON.stringify(r.errors)}`);
+ assert.deepStrictEqual(refused.touched, [], `${profile}: no SDK method is called`);
+ }
+});
+
// The web-resources phase reads contentPath files after the solution and tables are written, so a
// missing source must be caught here, with the page sources, before the first SDK call.
test('a web resource whose contentPath file is missing halts before any SDK call', async (t) => {
@@ -1493,6 +1537,74 @@ test('--authorize: each repeated key is read, matched case-insensitively, and ke
}
});
+test('--authorize overwrite:<configuration kind>:<key> approves replacing exactly one declared protected item\'s local copy, only under the opt-in', () => {
+ const { authorizationKeys } = require(path.join(__dirname, '..', 'build-model-app.js'));
+ const spec = (over = {}) => ({
+ configurationIdentity: 'stable-v1',
+ customApis: [{ uniqueName: 'contoso_Calc' }],
+ environmentVariables: [{ schemaName: 'contoso_ApiBase', type: 'string' }],
+ connectionReferences: [{ logicalName: 'contoso_sp', connectorId: '/providers/Microsoft.PowerApps/apis/shared_sharepointonline' }],
+ duplicateDetectionRules: [{ key: 'Email rule', name: 'Same email', entity: 'contact', conditions: [{ key: 'e', column: 'emailaddress1', match: 'exact' }] }],
+ ...over,
+ });
+ const ok = authorizationKeys(['--authorize', 'overwrite:customApi:CONTOSO_CALC', '--authorize=overwrite:environmentVariable:contoso_apibase',
+ '--authorize', 'overwrite:connectionReference:contoso_SP', '--authorize', 'overwrite:duplicateRule:Email rule'], spec());
+ assert.strictEqual(ok.error, null);
+ // Stored as the preflight asks for it: <kind>:<port key> (a name in lower case, a rule's key byte for byte).
+ assert.deepStrictEqual([...ok.overwrite].sort(), ['connectionReference:contoso_sp', 'customApi:contoso_calc', 'duplicateRule:Email rule', 'environmentVariable:contoso_apibase']);
+ assert.strictEqual(ok.keys.size, 0, 'an overwrite consents to no destructive change');
+ assert.strictEqual(ok.adopt.size, 0);
+ for (const [key, over, why] of [
+ ['overwrite:duplicateRule:email rule', {}, /names a configuration item the spec does not declare/],
+ ['overwrite:customApi:contoso_Other', {}, /names a configuration item the spec does not declare/],
+ ['overwrite:customApi:contoso_Calc', { configurationIdentity: undefined }, /does not set configurationIdentity "stable-v1"/],
+ ]) {
+ const r = authorizationKeys(['--authorize', key], spec(over));
+ assert.match(r.error || '', why, key);
+ assert.strictEqual(r.overwrite.size, 0, key);
+ }
+});
+
+test('--authorize adopt:<configuration kind>:... approves binding exactly the one protected row it names, as the stop printed it, only under the opt-in', () => {
+ const { authorizationKeys } = require(path.join(__dirname, '..', 'build-model-app.js'));
+ const spec = (over = {}) => ({
+ configurationIdentity: 'stable-v1',
+ customApis: [{ uniqueName: 'contoso_Calc', requestParameters: [{ uniqueName: 'A', type: 'String' }], responseProperties: [{ uniqueName: 'Total', type: 'Integer' }] }],
+ environmentVariables: [{ schemaName: 'contoso_ApiBase', type: 'string', value: 'x' }],
+ duplicateDetectionRules: [{ key: 'Email rule', name: 'Same email', entity: 'contact', conditions: [{ key: 'e', column: 'emailaddress1', match: 'exact' }] }],
+ ...over,
+ });
+ const ok = authorizationKeys(['--authorize', 'adopt:customApi:CONTOSO_CALC', '--authorize=adopt:customApiRequestParameter:contoso_calc/request%3AA',
+ '--authorize', 'adopt:customApiResponseProperty:Contoso_Calc/response%3Atotal', '--authorize', 'adopt:environmentVariableValue:contoso_apibase/value',
+ '--authorize', 'adopt:duplicateRuleCondition:Email%20rule/e'], spec());
+ assert.strictEqual(ok.error, null);
+ // Stored in the stop's own spelling (a name and a parameter in lower case, a rule's and a condition's key byte for byte, both parts
+ // percent-encoded), one row each: the root's approval covers none of its children.
+ assert.deepStrictEqual([...ok.configurationApprovals].sort(), [
+ 'adopt:customApi:contoso_calc', 'adopt:customApiRequestParameter:contoso_calc/request%3Aa', 'adopt:customApiResponseProperty:contoso_calc/response%3Atotal',
+ 'adopt:duplicateRuleCondition:Email%20rule/e', 'adopt:environmentVariableValue:contoso_apibase/value',
+ ]);
+ assert.strictEqual(ok.adopt.size, 0, 'a configuration row approval adopts no view or chart');
+ assert.strictEqual(ok.overwrite.size, 0);
+ assert.strictEqual(ok.keys.size, 0);
+ for (const [key, over, why] of [
+ ['adopt:customApi:contoso_Other', {}, /names a configuration item the spec does not declare/],
+ ['adopt:customApiRequestParameter:contoso_calc/request%3Ab', {}, /names a configuration item the spec does not declare/],
+ ['adopt:customApiResponseProperty:contoso_calc/request%3Aa', {}, /names a configuration item the spec does not declare/],
+ ['adopt:duplicateRuleCondition:email%20rule/e', {}, /names a configuration item the spec does not declare/],
+ ['adopt:environmentVariableValue:contoso_apibase/default', {}, /names a configuration item the spec does not declare/],
+ ['adopt:customApiRequestParameter:contoso_calc', {}, /is not adopt:<kind>:<declared key> or adopt:<child kind>/],
+ ['adopt:customApiRequestParameter:contoso_calc/request%3Aa/x', {}, /is not adopt:<kind>:<declared key> or adopt:<child kind>/],
+ ['adopt:customApiRequestParameter:contoso_calc/%E0%A4%A', {}, /is not adopt:<kind>:<declared key> or adopt:<child kind>/],
+ ['adopt:customApi:contoso_Calc', { configurationIdentity: undefined }, /does not set configurationIdentity "stable-v1", so there is no such row to bind/],
+ ['adopt:duplicateRuleCondition:Email%20rule/e', { configurationIdentity: undefined }, /does not set configurationIdentity "stable-v1", so there is no such row to bind/],
+ ]) {
+ const r = authorizationKeys(['--authorize', key], spec(over));
+ assert.match(r.error || '', why, key);
+ assert.strictEqual(r.configurationApprovals.size, 0, key);
+ }
+});
+
test('--authorize adopt:/overwrite: approve exactly the declared view or chart they name, in separate sets, under its family', () => {
const { authorizationKeys } = require(path.join(__dirname, '..', 'build-model-app.js'));
const spec = {
@@ -2709,7 +2821,8 @@ test('makeSdk\u2019s return shape and main\u2019s destructure stay in agreement'
test('the build verifies dashboards through makeSdk\u2019s isolated reader, sharing the build\u2019s client', () => {
const src = fs.readFileSync(path.join(__dirname, '..', 'build-model-app.js'), 'utf8');
const body = src.slice(src.indexOf('async function makeSdk'), src.indexOf('return { sdk, provisionSdk'));
- assert.match(body, /const httpClient = createAzHttpClient\(env, \{ throttle, sendOnce: \(method, url\) => isTranslationExport\(method, url\) \|\| configurationSendOnce\(method, url\), \.\.\.\(publicationBarrier \? \{ request: publicationBarrier\.gateRequest\(sendObserver \? sendObserver\.wrap\(\) : undefined\) \} : \{\}\), \.\.\.\(workflowEffectGate \? \{ workflowEffectGate \} : \{\}\) \}\);/, '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 with the build\u2019s workflow effect gate only when it has one');
+ assert.match(body, /const writeGate = managedCreateGate \? require\('\.\/lib\/managed-create-transport\.js'\)\.composeWriteGates\(workflowEffectGate, managedCreateGate\) : workflowEffectGate;/, 'the workflow effect gate alone unless protected configuration\u2019s managed create gate was made, and then both, composed into the one slot');
+ assert.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');
diff --git a/plugins/model-apps/scripts/tests/changed-only-flow.test.js b/plugins/model-apps/scripts/tests/changed-only-flow.test.js
index 4d8a4e056..387971b04 100644
--- a/plugins/model-apps/scripts/tests/changed-only-flow.test.js
+++ b/plugins/model-apps/scripts/tests/changed-only-flow.test.js
@@ -338,6 +338,24 @@ test('run: NOOP does not call buildModelApp and reports up-to-date', async () =>
} finally { rm(dir); }
});
+// Protected configuration's checks and edits run only in the full build (build-model-app.js, which never enters this flow while its
+// managed-create gate exists): any caller that hands the flow that gate gets a full build, never a no-op or a fast apply.
+test('run: with protected configuration in play (a managed-create gate) neither a NOOP nor a FAST apply is taken — the full build runs', async () => {
+ for (const content of ['v1', 'v2']) {
+ const dir = ws();
+ try {
+ seedEligible(dir, annotate(baseSpec(), 'v1'));
+ const record = [];
+ const r = await flow.runChangedOnlyApply({ spec: baseSpec(), opts: { workspaceDir: dir, apply: true }, deps: { ...baseDeps(dir, { buildModelApp: stubBuild(record), readContent: readFor(content) }), managedCreateGate: {} } });
+ assert.notStrictEqual(r.noop, true, content);
+ assert.strictEqual(r.changedOnly.decision, 'full', content);
+ assert.strictEqual(r.changedOnly.reason, flow.PROTECTED_CONFIGURATION_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/configuration-build-real-bundle.test.js b/plugins/model-apps/scripts/tests/configuration-build-real-bundle.test.js
index 5749cef5c..bc0afc09a 100644
--- a/plugins/model-apps/scripts/tests/configuration-build-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/configuration-build-real-bundle.test.js
@@ -4,19 +4,27 @@
// solution.version, end to end: buildModelApp -> runSdkBuild -> the configuration runtime (lib/configuration-build.js)
// -> the REAL maker-SDK bundle -> the strict in-memory org (tests/helpers/fake-config-org.js), which answers only the
// requests it models and lists every other one in `unexpected`. The build's own create port is the plain pass-through
-// (lib/creates-passthrough.js); every build runs with the stable-id create modules made unloadable, so a request for
-// one fails the test (tests/helpers/no-stable-create-modules.js).
+// (lib/creates-passthrough.js); every build of a spec without `configurationIdentity` runs with the stable-id create
+// modules made unloadable, so a request for one fails the test (tests/helpers/no-stable-create-modules.js).
+//
+// The `protected configuration through the build command` tests opt in (`configurationIdentity: "stable-v1"`) and run
+// the production command (main) with the real bundle: the command makes the managed create gate itself, and one app
+// directory carries the binding store from one run to the next, as the maker's workspace does between processes.
const test = require('node:test');
const assert = require('node:assert/strict');
const path = require('node:path');
+const fs = require('node:fs');
+const { fork } = require('node:child_process');
const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { runCommand: runCommandIn } = require('./helpers/configuration-command.js');
const { createAzHttpClient } = require('../lib/sdk-http-client.js');
const { createMakerSdk, createNodeWorkspaceStorage } = require('../lib/maker-sdk.js');
const { createConfigOrg } = require('./helpers/fake-config-org.js');
const { withoutStableCreateModules } = require('./helpers/no-stable-create-modules.js');
const { configurationSendOnce } = require('../lib/configuration-transport.js');
const { readDeploymentBindings } = require('../lib/configuration-artifacts.js');
+const { openManagedBindings } = require('../lib/managed-bindings.js');
const { buildModelApp, isTransientHalt, authorizationKeys } = require('../build-model-app.js');
const { runSdkBuild } = require('../lib/sdk-build.js');
const { STAGES } = require('../lib/stages.js');
@@ -420,66 +428,15 @@ test('a spec without the configuration fields sends no configuration request and
// engine an SDK they prepared, so they never meet the solution-scoped instance the command builds. Only what reaches outside the process
// is a double: the transport (the strict org above, behind the plugin's own az-token client), the identity check, the language read, the
// page backend and telemetry. Each SDK the command makes is watched for `initWorkspace`, which reads and writes local files only.
-const commandOrg = () => createConfigOrg({
+const commandOrg = (extra = {}) => createConfigOrg({
+ ...extra,
tables: [{ logicalName: 'contact', attributes: ['emailaddress1', 'lastname'] }],
solution: { uniqueName: 'ContosoSol', version: '1.0.0.0', prefix: 'contoso' },
});
-// `--allow-destructive` skips the read-only collision check, whose reads (app modules, forms) this org does not model; nothing here deletes.
-function runCommand(spec, { org = commandOrg(), apply = true, appDir = path.join(makeTempDir('config-command-'), 'app'), argv = ['--stage', 'data', '--allow-destructive'] } = {}) {
- const { loadCli } = require('./helpers/cli-harness.js');
- const fs = require('node:fs');
- const realHttp = require('../lib/sdk-http-client.js');
- const realMakerSdk = require('../lib/maker-sdk.js');
- fs.mkdirSync(appDir, { recursive: true });
- const specPath = path.join(appDir, 'app-spec.json');
- fs.writeFileSync(specPath, JSON.stringify(spec));
- const sdks = [];
- const scripts = path.join(__dirname, '..');
- const authCli = loadCli(path.join(scripts, 'lib', 'dataverse-auth.js'));
- const cli = loadCli(path.join(scripts, 'build-model-app.js'), {
- argv: ['--env', org.origin, '--spec', `@${specPath}`, ...(apply ? ['--apply'] : []), '--non-interactive', ...argv],
- env: { PATH: path.dirname(process.execPath), POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1' },
- requires: {
- './lib/dataverse-auth.js': { ...authCli.exports, preflightAuth: async () => ({ ok: true }) },
- './lib/entity-provision.js': { ...require('../lib/entity-provision.js'), resolveAuthoringLanguage: async () => 1033 },
- './lib/sdk-http-client.js': {
- ...realHttp,
- createAzHttpClient: (env, o = {}) => realHttp.createAzHttpClient(env, { ...o, getToken: () => 'test-token-0123456789abcdef', request: (req) => org.request(req), sleep: async () => {} }),
- },
- './lib/maker-sdk.js': {
- ...realMakerSdk,
- createMakerSdk: (o) => {
- const sdk = realMakerSdk.createMakerSdk(o);
- const seen = { scoped: !!o.solutionUniqueName, inits: 0, requestsAtInit: [] };
- const init = sdk.initWorkspace.bind(sdk);
- sdk.initWorkspace = async () => {
- seen.inits += 1;
- const before = org.requests.length;
- await init();
- seen.requestsAtInit.push(org.requests.length - before);
- };
- sdks.push(seen);
- return sdk;
- },
- },
- './lib/genpage-sdk.js': { ...require('../lib/genpage-sdk.js'), makeGenpageSdk: () => ({ dispose: async () => ({ left: [] }) }) },
- './lib/telemetry/skill-completed.js': { ...require('../lib/telemetry/skill-completed.js'), emitSkillCompleted: async () => {} },
- },
- });
- return (async () => {
- let exitCode;
- let thrown;
- try {
- await cli.main();
- } catch (e) {
- if (e && e.exitCode !== undefined) exitCode = e.exitCode;
- else thrown = e;
- }
- let payload;
- try { payload = JSON.parse(authCli.stdoutText()); } catch { payload = undefined; }
- return { org, appDir, sdks, exitCode, thrown, payload, stderr: [...cli.stderr, ...authCli.stderr].join('') };
- })();
+// One invocation of the command (helpers/configuration-command.js) over `org` and the app folder `appDir`, a new one of each by default.
+function runCommand(spec, { org = commandOrg(), appDir = path.join(makeTempDir('config-command-'), 'app'), ...options } = {}) {
+ return runCommandIn(spec, { org, appDir, ...options });
}
test('the build command creates a declared environment variable through the SDK it makes itself, and prepares that SDK\u2019s workspace without a request', async () => {
@@ -531,4 +488,890 @@ test('the build command leaves the solution-scoped SDK\u2019s workspace unprepar
assert.equal(scoped[0].inits, 0, 'nothing is prepared that the spec does not use');
assert.deepEqual(out.org.requests.filter((r) => CONFIGURATION_PATH.test(String(r.path))).map((r) => `${r.method} ${r.path}`), []);
assert.deepEqual(out.org.unexpected, []);
+});
+
+// Protected configuration identities (configurationIdentity "stable-v1") through the build COMMAND: the deferred managed-create gate
+// the command makes for them, bound to the app folder's binding store, and the configuration hookup the engine builds over both. Each
+// runCommand is a new invocation (a new gate, context, SDK and throwaway SDK workspace) over the same app folder, so the binding store
+// carries over between them as it does between processes; the org lives on. Nothing here reaches outside the process.
+const PROTECTED_ROWS = ['environmentvariabledefinitions', 'customapis', 'customapirequestparameters', 'customapiresponseproperties', 'duplicaterules', 'duplicateruleconditions'];
+const PROTECTED_MODULE = /(^|[\\/])(managed-create-(transport|context|batch)|configuration-protected|configuration-create-bindings)(\.js)?$/;
+function protectedSpec(over = {}) {
+ const spec = { ...makeSpec(), configurationIdentity: 'stable-v1', ...over };
+ // A connection reference's binding is proven through the Power Apps service, which this command reaches outside the process.
+ delete spec.connectionReferences;
+ return spec;
+}
+const rowCounts = (org) => Object.fromEntries(PROTECTED_ROWS.map((set) => [set, org.rows(set).length]));
+// The root creates (a Custom API's and a rule's children ride in their root's body): `org.writes` lists `METHOD path` without the query.
+const rootCreates = (org, since = 0) => org.writes(since).filter((w) => /^POST \/(environmentvariabledefinitions|environmentvariablevalues|customapis|duplicaterules)$/.test(w));
+const runAgain = (spec, base, argv) => runCommand(spec, { org: base.org, appDir: base.appDir, ...(argv ? { argv } : {}) });
+const DATA = ['--stage', 'data', '--allow-destructive'];
+const authorize = (tokens) => tokens.flatMap((t) => ['--authorize', t]);
+// Every module the run asked for by a protected name, cached or not (Module.prototype.require sees both).
+async function protectedModulesLoadedBy(fn) {
+ const Module = require('node:module');
+ const requested = [];
+ const original = Module.prototype.require;
+ Module.prototype.require = function recordProtected(id) {
+ if (typeof id === 'string' && PROTECTED_MODULE.test(id)) requested.push(id);
+ return original.apply(this, arguments);
+ };
+ try {
+ return { result: await fn(), requested };
+ } finally {
+ Module.prototype.require = original;
+ }
+}
+
+test('protected configuration through the build command: every root and child create carries its derived id, the ids are bound, and a later run sends no create', async () => {
+ const out = await runCommand(protectedSpec());
+ assert.equal(out.thrown && out.thrown.message, undefined, 'the build did not halt');
+ assert.equal(out.exitCode, 0, out.stderr.slice(-600));
+ const bound = out.payload.created.configuration.managedBindings;
+ assert.deepEqual(bound.map((b) => `${b.kind}:${b.key}:${b.origin}`).sort(),
+ ['customApi:contoso_Calc:created', 'duplicateRule:email:created', 'environmentVariable:contoso_ApiBase:created', 'environmentVariable:contoso_ApiKey:created']);
+ const of = (kind, key) => bound.find((b) => b.kind === kind && b.key === key);
+ const posted = (set) => out.org.requests.filter((r) => r.method === 'POST' && String(r.path).split('?')[0] === `/${set}`).map((r) => r.body);
+ assert.deepEqual(posted('environmentvariabledefinitions').map((b) => b.environmentvariabledefinitionid).sort(),
+ [of('environmentVariable', 'contoso_ApiBase').id, of('environmentVariable', 'contoso_ApiKey').id].sort());
+ const [api] = posted('customapis');
+ assert.equal(api.customapiid, of('customApi', 'contoso_Calc').id);
+ assert.equal(api.CustomAPIRequestParameters[0].customapirequestparameterid, of('customApi', 'contoso_Calc').childIds['request:a']);
+ assert.equal(api.CustomAPIResponseProperties[0].customapiresponsepropertyid, of('customApi', 'contoso_Calc').childIds['response:r']);
+ const [rule] = posted('duplicaterules');
+ assert.equal(rule.duplicateruleid, of('duplicateRule', 'email').id);
+ assert.equal(rule.DuplicateRule_DuplicateRuleConditions[0].duplicateruleconditionid, of('duplicateRule', 'email').childIds.e);
+ // The rows are where the bindings say.
+ assert.equal(out.org.rows('customapis')[0].customapiid, api.customapiid);
+ assert.equal(out.org.rows('duplicaterules')[0].duplicateruleid, rule.duplicateruleid);
+ // The ids are derived, not minted: the same App Spec on another org at the same address gets the same ones.
+ const elsewhere = await runCommand(protectedSpec());
+ assert.deepEqual(elsewhere.payload.created.configuration.managedBindings.map((b) => b.id), bound.map((b) => b.id));
+
+ const mark = out.org.requests.length;
+ const again = await runAgain(protectedSpec(), out);
+ assert.equal(again.thrown && again.thrown.message, undefined, 'the rerun did not halt');
+ assert.equal(again.exitCode, 0, again.stderr.slice(-600));
+ assert.deepEqual(out.org.writes(mark), [], 'an unchanged rerun writes nothing');
+ assert.deepEqual(rowCounts(out.org), { environmentvariabledefinitions: 2, customapis: 1, customapirequestparameters: 1, customapiresponseproperties: 1, duplicaterules: 1, duplicateruleconditions: 1 });
+ assert.deepEqual(out.org.unexpected, []);
+});
+
+test('protected configuration through the build command: a create whose answer was lost is never sent again, and its rows are bound only under their exact approvals', async () => {
+ let org = null;
+ let sends = 0;
+ let replaying = false;
+ // The service applies the Custom API's first create, and its answer is lost on the way back (a gateway's 503). `sends` counts the
+ // creates the build sent; the intercept's own replay of that one request into the org is not one of them.
+ org = commandOrg({ intercept: async (req) => {
+ if (replaying || req.method !== 'POST' || req.path.split('?')[0] !== '/customapis') return undefined;
+ sends += 1;
+ if (sends > 1) return undefined;
+ replaying = true;
+ try {
+ await org.request({ url: `${org.origin}/api/data/v9.0${req.path}`, method: 'POST', headers: req.headers, body: JSON.stringify(req.body) });
+ } finally {
+ replaying = false;
+ }
+ return { statusCode: 503, body: { error: { code: '0x80040216', message: 'the answer was lost' } } };
+ } });
+ const first = await runCommand(protectedSpec(), { org });
+ assert.match(String(first.thrown && first.thrown.message), /customApi contoso_Calc \(create-outcome-unknown\)/);
+ assert.equal(sends, 1, 'sent once, never re-sent on the 503');
+ assert.deepEqual(rowCounts(org), { environmentvariabledefinitions: 2, customapis: 1, customapirequestparameters: 1, customapiresponseproperties: 1, duplicaterules: 0, duplicateruleconditions: 0 });
+
+ // A fresh invocation never creates it again: the row has no proof yet, so it must first be completed under the same ids.
+ let mark = org.requests.length;
+ const rerun = await runAgain(protectedSpec(), first);
+ assert.equal(rerun.thrown && rerun.thrown.code, 'create-completion-required', rerun.thrown && rerun.thrown.message);
+ assert.deepEqual(org.writes(mark), []);
+
+ // The maker completes it (its children's solution membership), as the stop asks.
+ const store = openManagedBindings({ workspaceDir: path.join(first.appDir, '.maker-workspace'), environment: org.origin, appUniqueName: 'contoso_configprobe', solutionUniqueName: 'ContosoSol' });
+ const inSolution = new Set(org.rows('solutioncomponents').map((c) => c.objectid));
+ for (const m of store.readGroup('customApi', 'contoso_calc').pending.rowProtocol.completion.members) {
+ if (inSolution.has(m.id)) continue;
+ await org.request({ url: `${org.origin}/api/data/v9.2/AddSolutionComponent`, method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ SolutionUniqueName: 'ContosoSol', ComponentId: m.id, ComponentType: m.componentType, AddRequiredComponents: false }) });
+ }
+
+ // No answer proved those rows this build's own: the next run asks for each row's exact approval and sends nothing.
+ mark = org.requests.length;
+ const asked = await runAgain(protectedSpec(), first);
+ assert.equal(asked.thrown && asked.thrown.code, 'create-ownership-required', asked.thrown && asked.thrown.message);
+ assert.deepEqual(org.writes(mark), []);
+ const quoted = /given after checking those rows are yours: (.*)\.$/.exec(asked.thrown.message);
+ assert.ok(quoted, asked.thrown.message);
+ const tokens = JSON.parse(`[${quoted[1]}]`);
+ assert.deepEqual(tokens.slice().sort(), ['adopt:customApi:contoso_calc', 'adopt:customApiRequestParameter:contoso_calc/request%3Aa', 'adopt:customApiResponseProperty:contoso_calc/response%3Ar']);
+
+ // A root's approval does not cover its children, and a mistyped or unprotected token is refused before anything is read.
+ mark = org.requests.length;
+ const partial = await runAgain(protectedSpec(), first, [...DATA, ...authorize(['adopt:customApi:contoso_Calc'])]);
+ assert.equal(partial.thrown && partial.thrown.code, 'create-ownership-required');
+ assert.deepEqual(org.writes(mark), []);
+ const typo = await runAgain(protectedSpec(), first, [...DATA, ...authorize(['adopt:customApiRequestParameter:contoso_calc/request%3Ab'])]);
+ assert.equal(typo.exitCode, 1, typo.stderr.slice(-600));
+ assert.match(`${typo.stderr} ${JSON.stringify(typo.payload)}`, /adopt:customApiRequestParameter:contoso_calc\/request%3Ab/);
+ assert.deepEqual(org.writes(mark), []);
+
+ // The printed approvals, typed in the App Spec's own case, bind those rows: nothing is created again; the rule left behind is made.
+ const typed = tokens.map((t) => t.replace('contoso_calc', 'contoso_Calc'));
+ const done = await runAgain(protectedSpec(), first, [...DATA, ...authorize(typed)]);
+ assert.equal(done.thrown && done.thrown.message, undefined, 'the approved run did not halt');
+ assert.equal(done.exitCode, 0, done.stderr.slice(-600));
+ assert.equal(sends, 1, 'the Custom API is never sent again');
+ assert.deepEqual(rootCreates(org, mark), ['POST /duplicaterules']);
+ assert.deepEqual(rowCounts(org), { environmentvariabledefinitions: 2, customapis: 1, customapirequestparameters: 1, customapiresponseproperties: 1, duplicaterules: 1, duplicateruleconditions: 1 });
+ // The approved rows are this build's now, in the binding store, at the ids they were created with.
+ const reread = openManagedBindings({ workspaceDir: path.join(first.appDir, '.maker-workspace'), environment: org.origin, appUniqueName: 'contoso_configprobe', solutionUniqueName: 'ContosoSol' });
+ const group = reread.readGroup('customApi', 'contoso_calc');
+ assert.equal(group.pending, null);
+ assert.deepEqual(group.committed.records.map((r) => r.id).sort(), [org.rows('customapis')[0].customapiid, org.rows('customapirequestparameters')[0].customapirequestparameterid, org.rows('customapiresponseproperties')[0].customapiresponsepropertyid].sort());
+ assert.deepEqual(org.unexpected, []);
+});
+
+test('protected configuration through the build command: a later phase\u2019s transient failure runs the whole build again and the configuration rows stay where they are', async () => {
+ let refused = 0;
+ // The sample data's first create meets a customization lock, which the build retries whole; the second succeeds.
+ const org = commandOrg({ intercept: ({ method, path: p }) => {
+ if (/^\/EntityDefinitions\(LogicalName='contact'\)\/Attributes/.test(p)) return { statusCode: 200, body: { value: [] } };
+ if (method !== 'POST' || !/^\/contacts\//.test(p)) return undefined;
+ refused += 1;
+ return refused === 1
+ ? { statusCode: 400, body: { error: { code: '0x80071151', message: 'CustomizationLockException: another operation is running, try again later' } } }
+ : { statusCode: 200, body: { Ids: ['11111111-2222-3333-4444-555555555555'] } };
+ } });
+ const spec = protectedSpec({ entities: [{ schemaName: 'contact', displayName: 'Contact', existing: true, primaryAttribute: { schemaName: 'fullname', displayName: 'Full Name' } }], sampleData: { contact: [{ lastname: 'Probe' }] } });
+ const out = await runCommand(spec, { org, argv: [...DATA, '--sample-data'] });
+ assert.equal(out.thrown && out.thrown.message, undefined, out.stderr.slice(-900));
+ assert.equal(out.exitCode, 0, out.stderr.slice(-900));
+ assert.match(out.stderr, /transient error in sample-data — retrying \(attempt 1\/3\)/);
+ assert.equal(refused, 2, 'the sample data was sent by two attempts');
+ // The second attempt found every configuration row at its bound id: one create each, over both attempts.
+ assert.deepEqual(rootCreates(org).sort(), ['POST /customapis', 'POST /duplicaterules', 'POST /environmentvariabledefinitions', 'POST /environmentvariabledefinitions']);
+ assert.equal(org.writes().filter((w) => /PublishDuplicateRule$/.test(w)).length, 1, 'the rule is published once');
+ assert.deepEqual(rowCounts(org), { environmentvariabledefinitions: 2, customapis: 1, customapirequestparameters: 1, customapiresponseproperties: 1, duplicaterules: 1, duplicateruleconditions: 1 });
+ // The second attempt changed nothing: it found each row at the id the first one bound.
+ const outcome = out.payload.created.configuration;
+ assert.deepEqual(outcome.saved, []);
+ assert.deepEqual(outcome.unchanged.map((u) => u.id).sort(), [...org.rows('environmentvariabledefinitions').map((r) => r.environmentvariabledefinitionid), org.rows('customapis')[0].customapiid, org.rows('duplicaterules')[0].duplicateruleid].sort());
+});
+
+test('protected configuration through the build command: an edit needs its exact field approval, and a field the approval does not name stays refused', async () => {
+ const out = await runCommand(protectedSpec());
+ assert.equal(out.exitCode, 0, out.stderr.slice(-600));
+ const edited = protectedSpec({ customApis: [{ ...CONFIGURATION_FIELDS.customApis[0], isPrivate: true }] });
+ let mark = out.org.requests.length;
+ for (const argv of [DATA, [...DATA, ...authorize(['customApi:contoso_Calc:executePrivilegeName'])]]) {
+ const refused = await runAgain(edited, out, argv);
+ assert.match(String(refused.thrown && refused.thrown.message), /customApi contoso_Calc \(DESTRUCTIVE_CHANGE_UNAUTHORIZED\) \(approve with --authorize customApi:contoso_calc:isPrivate\)/);
+ assert.deepEqual(out.org.writes(mark), []);
+ }
+ const id = out.org.rows('customapis')[0].customapiid;
+ const done = await runAgain(edited, out, [...DATA, ...authorize(['customApi:contoso_Calc:isPrivate'])]);
+ assert.equal(done.exitCode, 0, done.stderr.slice(-600));
+ assert.deepEqual(out.org.writes(mark), [`PATCH /customapis(${id})`], 'the one approved field, at the bound id');
+ assert.equal(out.org.rows('customapis')[0].isprivate, true);
+ mark = out.org.requests.length;
+ assert.equal((await runAgain(edited, out)).exitCode, 0);
+ assert.deepEqual(out.org.writes(mark), []);
+ assert.deepEqual(out.org.unexpected, []);
+});
+
+test('protected configuration through the build command: removing the opt-in, a missing bound row or an unreadable store stops the build before any write, whatever it selects', async () => {
+ const out = await runCommand(protectedSpec());
+ assert.equal(out.exitCode, 0, out.stderr.slice(-600));
+ const withoutOptIn = protectedSpec();
+ delete withoutOptIn.configurationIdentity;
+ // The version change would be the build's first write; it is not sent.
+ withoutOptIn.solution = { ...withoutOptIn.solution, version: '1.3.0.0' };
+ let mark = out.org.requests.length;
+ for (const argv of [DATA, ['--changed-only', '--allow-destructive']]) {
+ const stopped = await runAgain(withoutOptIn, out, argv);
+ assert.equal(stopped.thrown && stopped.thrown.code, 'create-identity-opt-in-required', `${argv.join(' ')}: ${stopped.thrown && stopped.thrown.message}`);
+ assert.match(stopped.thrown.message, /restore configurationIdentity "stable-v1"/);
+ assert.deepEqual(out.org.writes(mark), [], argv.join(' '));
+ }
+
+ // A bound row deleted outside the plugin is not replaced by a namesake.
+ const id = out.org.rows('customapis')[0].customapiid;
+ await out.org.request({ url: `${out.org.origin}/api/data/v9.2/customapis(${id})`, method: 'DELETE', headers: {} });
+ mark = out.org.requests.length;
+ const gone = await runAgain(protectedSpec({ solution: withoutOptIn.solution }), out);
+ assert.match(String(gone.thrown && gone.thrown.message), /the bound customApi of customApi "contoso_calc" \(.*\) is gone; it is not replaced by a namesake/);
+ assert.deepEqual(out.org.writes(mark), []);
+ assert.equal(out.org.rows('customapis').length, 0);
+
+ // A binding store the build cannot read stops it, with or without the opt-in.
+ const fs = require('node:fs');
+ const ws = path.join(out.appDir, '.maker-workspace');
+ const files = fs.readdirSync(ws).filter((f) => f.startsWith('managed-bindings.'));
+ assert.equal(files.length, 1);
+ fs.writeFileSync(path.join(ws, files[0]), '{');
+ for (const spec of [protectedSpec(), withoutOptIn]) {
+ const unreadable = await runAgain(spec, out);
+ assert.equal(unreadable.thrown && unreadable.thrown.code, 'managed-binding-store-unreadable', unreadable.thrown && unreadable.thrown.message);
+ assert.deepEqual(out.org.writes(mark), []);
+ }
+ assert.deepEqual(out.org.unexpected, []);
+});
+
+test('protected configuration through the build command: an App Spec that dropped an unfinished item still stops on it, whatever it selects', async () => {
+ let org = null;
+ let lose = true;
+ org = commandOrg({ intercept: async (req) => {
+ if (!lose || req.method !== 'POST' || req.path.split('?')[0] !== '/customapis') return undefined;
+ lose = false;
+ await org.request({ url: `${org.origin}/api/data/v9.0${req.path}`, method: 'POST', headers: req.headers, body: JSON.stringify(req.body) });
+ return { statusCode: 503, body: { error: { code: '0x80040216', message: 'the answer was lost' } } };
+ } });
+ const first = await runCommand(protectedSpec(), { org });
+ assert.match(String(first.thrown && first.thrown.message), /create-outcome-unknown/);
+ // Neither the opt-in nor any configuration item is left, and the version would be the first write.
+ const dropped = { ...makeSpec({ configuration: false }), solution: { ...makeSpec().solution, version: '1.3.0.0' } };
+ const mark = org.requests.length;
+ for (const argv of [DATA, ['--changed-only', '--allow-destructive']]) {
+ const stopped = await runAgain(dropped, first, argv);
+ assert.ok(stopped.thrown, `${argv.join(' ')}: the build stopped`);
+ assert.match(stopped.thrown.message, /customApi/, stopped.thrown.message);
+ assert.equal(stopped.thrown.phase, 'preflight', stopped.thrown.message);
+ assert.deepEqual(org.writes(mark), [], argv.join(' '));
+ }
+ assert.deepEqual(org.unexpected, []);
+});
+
+// A --changed-only apply over an ELIGIBLE snapshot that says nothing changed: the envelope the production writer leaves after an eligible
+// apply of `spec` (lib/apply-snapshot.js, written by lib/apply-snapshot-store.js), with the live identity that matches it. Without
+// protected configuration this is the flow's no-op, which sends nothing and calls no engine. `calls.n` counts the flow's identity lookups.
+const liveIdentityOf = (org) => ({ orgId: '11111111-2222-4333-8444-555555555555', envUrl: org.origin, appUniqueName: 'contoso_configprobe', appId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' });
+function seedEligibleSnapshot(appDir, spec, live) {
+ const snap = require('../lib/apply-snapshot.js');
+ const baseline = snap.makeEnvelope(live);
+ baseline.priorSpec = require('../lib/content-hash.js').annotateContentHashes(spec, () => null);
+ snap.markEligible(baseline);
+ require('../lib/apply-snapshot-store.js').writeSnapshotAtomic(path.join(appDir, '.maker-workspace'), baseline);
+}
+const CHANGED_ONLY = ['--changed-only', '--allow-destructive'];
+function changedOnlyAgain(spec, base, { argv = CHANGED_ONLY, calls } = {}) {
+ const liveIdentity = () => {
+ if (calls) calls.n += 1;
+ return liveIdentityOf(base.org);
+ };
+ return runCommand(spec, { org: base.org, appDir: base.appDir, argv, liveIdentity });
+}
+
+const NOOP_BYPASS = [
+ ['an unreadable binding store', 'managed-binding-store-unreadable', (out) => {
+ const fs = require('node:fs');
+ const ws = path.join(out.appDir, '.maker-workspace');
+ fs.writeFileSync(path.join(ws, fs.readdirSync(ws).find((f) => f.startsWith('managed-bindings.'))), '{');
+ }],
+ ['the opt-in removed', 'create-identity-opt-in-required', (out, next) => { delete next.configurationIdentity; }],
+ ['a bound row deleted', 'configuration-row-not-found', (out) => { out.org.sets.get('customapis').clear(); }],
+ ['an edit the protected path refuses', 'configuration-edit-unsupported', (out, next) => { next.duplicateDetectionRules[0].name = 'Changed rule label'; }],
+];
+for (const [variant, code, change] of NOOP_BYPASS) {
+ test(`protected configuration through the build command: a changed-only apply whose snapshot says nothing changed still stops on ${variant}, before any write`, async () => {
+ const spec = protectedSpec();
+ const out = await runCommand(spec);
+ assert.equal(out.exitCode, 0, out.stderr.slice(-600));
+ seedEligibleSnapshot(out.appDir, spec, liveIdentityOf(out.org));
+ const next = structuredClone(spec);
+ change(out, next);
+ const mark = out.org.requests.length;
+ const calls = { n: 0 };
+ const stopped = await changedOnlyAgain(next, out, { calls });
+ assert.equal(stopped.thrown && stopped.thrown.code, code, `${stopped.thrown && stopped.thrown.message} ${JSON.stringify(stopped.payload)}`);
+ assert.notEqual(stopped.payload && stopped.payload.noop, true, 'never the no-op success');
+ assert.deepEqual(out.org.writes(mark), []);
+ // The command took no changed-only decision at all: the flow (and its identity lookup) never ran.
+ assert.equal(calls.n, 0, 'the changed-only flow was not entered');
+ assert.match(stopped.stderr, /changed-only: FULL — protected configuration is in play/);
+ assert.deepEqual(out.org.unexpected, []);
+ });
+}
+
+// The fake org models the configuration endpoints only, so a whole build, which a protected --changed-only apply is, ends at the first
+// phase past them: the web-resources phase's read of the webresource table (a 404 here). Reaching it proves the apply ran whole, past
+// every configuration step, instead of the flow's no-op.
+const reachedWebResources = (r) => /EntityDefinitions\(LogicalName='webresource'\)/.test(String(r.thrown && r.thrown.message));
+test('protected configuration through the build command: a changed-only apply runs the whole build, so an approved edit is applied and the rerun sends nothing', async () => {
+ const spec = protectedSpec();
+ const out = await runCommand(spec);
+ assert.equal(out.exitCode, 0, out.stderr.slice(-600));
+ seedEligibleSnapshot(out.appDir, spec, liveIdentityOf(out.org));
+ // Nothing changed: still the whole build (its checks run), which finds every configuration row as declared and writes nothing.
+ let mark = out.org.requests.length;
+ const unchanged = await changedOnlyAgain(spec, out);
+ assert.ok(reachedWebResources(unchanged), `${unchanged.thrown && unchanged.thrown.message} ${JSON.stringify(unchanged.payload)}`);
+ assert.match(unchanged.stderr, /changed-only: FULL — protected configuration is in play/);
+ assert.deepEqual(out.org.writes(mark), []);
+ // An edit is refused without its approval and applied, at the bound id, with it.
+ const edited = protectedSpec({ customApis: [{ ...CONFIGURATION_FIELDS.customApis[0], isPrivate: true }] });
+ const refused = await changedOnlyAgain(edited, out);
+ assert.match(String(refused.thrown && refused.thrown.message), /approve with --authorize customApi:contoso_calc:isPrivate/);
+ assert.deepEqual(out.org.writes(mark), []);
+ const id = out.org.rows('customapis')[0].customapiid;
+ const done = await changedOnlyAgain(edited, out, { argv: [...CHANGED_ONLY, ...authorize(['customApi:contoso_Calc:isPrivate'])] });
+ assert.ok(reachedWebResources(done), done.thrown && done.thrown.message);
+ assert.deepEqual(out.org.writes(mark), [`PATCH /customapis(${id})`]);
+ assert.equal(out.org.rows('customapis')[0].isprivate, true);
+ mark = out.org.requests.length;
+ const again = await changedOnlyAgain(edited, out);
+ assert.ok(reachedWebResources(again), again.thrown && again.thrown.message);
+ assert.deepEqual(out.org.writes(mark), []);
+ assert.deepEqual(out.org.unexpected, []);
+});
+
+// Every way an apply can narrow itself still meets the protected checks before its first write, or is refused before it: none of them is an
+// exit that reports success over a pending obligation. The whole build, --stage data and --changed-only stop on the obligation; every other
+// phase range is refused by the apply's partial-range guard before anything is sent; a dry run plans and sends nothing.
+test('protected configuration through the build command: no phase selection, changed-only or dry run gets past a pending obligation', async () => {
+ const out = await runCommand(protectedSpec());
+ assert.equal(out.exitCode, 0, out.stderr.slice(-600));
+ seedEligibleSnapshot(out.appDir, protectedSpec(), liveIdentityOf(out.org));
+ out.org.sets.get('customapis').clear();
+ const mark = out.org.requests.length;
+ // --changed-only first, while the snapshot still says nothing changed (a stopped build marks it ineligible).
+ for (const argv of [CHANGED_ONLY, ['--allow-destructive'], DATA]) {
+ const stopped = await changedOnlyAgain(protectedSpec(), out, { argv });
+ assert.equal(stopped.thrown && stopped.thrown.code, 'configuration-row-not-found', `${argv.join(' ')}: ${stopped.thrown && stopped.thrown.message}`);
+ assert.deepEqual(out.org.writes(mark), [], argv.join(' '));
+ }
+ const ranges = [['--stage', 'ui'], ['--stage', 'app'], ['--stage', 'publish'], ['--only', 'pages'], ['--skip', 'data-model'], ['--only', 'sample-data', '--sample-data'], ['--from', 'views']];
+ for (const range of ranges) {
+ const refused = await changedOnlyAgain(protectedSpec(), out, { argv: [...range, '--allow-destructive'] });
+ assert.equal(refused.exitCode, 1, `${range.join(' ')}: ${refused.thrown && refused.thrown.message}`);
+ assert.equal(refused.payload && refused.payload.ok, false, range.join(' '));
+ assert.match(String(refused.payload.errors), /refusing to apply a partial phase range/, range.join(' '));
+ assert.deepEqual(out.org.writes(mark), [], range.join(' '));
+ }
+ await runCommand(protectedSpec(), { org: out.org, appDir: out.appDir, apply: false, argv: ['--stage', 'data'] });
+ assert.deepEqual(out.org.writes(mark), [], 'a dry run sends nothing');
+ assert.deepEqual(out.org.unexpected, []);
+});
+
+test('a build without the opt-in and without stored configuration rows loads no protected module and sends what it always sent', async () => {
+ const spec = makeSpec();
+ delete spec.connectionReferences;
+ const { result: out, requested } = await protectedModulesLoadedBy(() => runCommand(spec));
+ assert.deepEqual(requested, [], 'no protected configuration module is loaded');
+ assert.equal(out.exitCode, 0, out.stderr.slice(-600));
+ // The plain path: the server mints each id (no id in the create's body).
+ const [api] = out.org.requests.filter((r) => r.method === 'POST' && String(r.path).split('?')[0] === '/customapis').map((r) => r.body);
+ // The plain path: the ids are minted at random (version 4), not derived from the item (the protected path's name-based version 5).
+ const saved = out.payload.created.configuration.saved;
+ assert.equal(saved.length, 4);
+ for (const s of saved) assert.match(s.id, /^[0-9a-f]{8}-[0-9a-f]{4}-4/, `${s.kind} ${s.key}`);
+ assert.ok(!/configurationIdentity|managed-create|adopt:/.test(out.stderr));
+ const again = await protectedModulesLoadedBy(() => runAgain(spec, out));
+ assert.deepEqual(again.requested, []);
+ assert.equal(again.result.exitCode, 0);
+ assert.deepEqual(out.org.unexpected, []);
+
+ // Its changed-only apply over an eligible snapshot that says nothing changed is still the flow's no-op: no engine, no request, no
+ // protected module. A configuration item changed since that snapshot is a full build, never that no-op (lib/phase-diff.js).
+ seedEligibleSnapshot(out.appDir, spec, liveIdentityOf(out.org));
+ const mark = out.org.requests.length;
+ const calls = { n: 0 };
+ const noop = await protectedModulesLoadedBy(() => changedOnlyAgain(spec, out, { calls }));
+ assert.deepEqual(noop.requested, []);
+ assert.equal(noop.result.exitCode, 0, noop.result.thrown && noop.result.thrown.message);
+ assert.equal(noop.result.payload.noop, true);
+ assert.equal(calls.n, 1, 'the flow decided');
+ assert.equal(out.org.requests.length, mark, 'nothing was sent');
+ const edited = { ...spec, customApis: [{ ...spec.customApis[0], displayName: 'Calculate again' }] };
+ const full = await protectedModulesLoadedBy(() => changedOnlyAgain(edited, out));
+ assert.deepEqual(full.requested, []);
+ assert.notEqual(full.result.payload && full.result.payload.noop, true, 'a configuration edit is never the no-op');
+ assert.match(full.result.stderr, /changed-only: FULL — full build — data-model: changed/);
+ assert.deepEqual(out.org.unexpected, []);
+});
+
+// The build command in separate OS processes over one app folder (helpers/configuration-command-child.js): only what reached the disk
+// (the binding store under the app folder) carries a build's state to the next, never anything a process held in memory. The service is
+// the strict org in this process, which every child reaches over its IPC channel. Each child's temporary folder (TEMP/TMP) is this test's
+// own folder, so the throwaway SDK workspace each command makes is made there and must be gone when the command ends.
+function processCommands() {
+ const root = makeTempDir('config-process-');
+ const env = { ...process.env, TEMP: root, TMP: root, TMPDIR: root, POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1' };
+ delete env.NODE_TEST_CONTEXT;
+ const pids = [];
+ let runs = 0;
+ const command = (org, spec, { argv } = {}) => new Promise((resolve, reject) => {
+ const n = ++runs;
+ const logFile = path.join(root, `child-${n}.log`);
+ const log = fs.openSync(logFile, 'w');
+ const child = fork(path.join(__dirname, 'helpers', 'configuration-command-child.js'), [], { cwd: path.join(__dirname, '..'), env, stdio: ['ignore', log, log, 'ipc'] });
+ let result;
+ child.on('message', async (m) => {
+ if (m.request) {
+ try {
+ child.send({ reply: m.request, answer: await org.request(m.req) });
+ } catch (e) {
+ child.kill();
+ reject(e);
+ }
+ } else if (m.result) {
+ result = m.result;
+ }
+ });
+ child.on('error', reject);
+ child.on('exit', (code) => {
+ fs.closeSync(log);
+ if (code !== 0 || !result) return reject(new Error(`command ${n} exited ${code}: ${fs.readFileSync(logFile, 'utf8').slice(-1500)}`));
+ pids.push(result.pid);
+ assert.ok(result.workspaceDirs.length > 0 && result.workspacesRemoved, `command ${n} removed the throwaway SDK workspace it made: ${result.workspaceDirs}`);
+ assert.ok(result.workspaceDirs.every((dir) => path.resolve(dir).startsWith(path.resolve(root))), `command ${n} made its SDK workspace in the test's folder`);
+ resolve(result);
+ });
+ child.send({ start: { origin: org.origin, spec, appDir: path.join(root, 'app'), argv } });
+ });
+ return { root, appDir: path.join(root, 'app'), pids, command };
+}
+
+test('protected configuration in fresh processes: a whole-build retry keeps every id, and a later process reopening the folder sends nothing', async () => {
+ const p = processCommands();
+ let refused = 0;
+ const org = commandOrg({ intercept: ({ method, path: at }) => {
+ if (/^\/EntityDefinitions\(LogicalName='contact'\)\/Attributes/.test(at)) return { statusCode: 200, body: { value: [] } };
+ if (method !== 'POST' || !/^\/contacts\//.test(at)) return undefined;
+ refused += 1;
+ return refused === 1
+ ? { statusCode: 400, body: { error: { code: '0x80071151', message: 'CustomizationLockException: another operation is running, try again later' } } }
+ : { statusCode: 200, body: { Ids: ['11111111-2222-3333-4444-555555555555'] } };
+ } });
+ const spec = protectedSpec({ entities: [{ schemaName: 'contact', displayName: 'Contact', existing: true, primaryAttribute: { schemaName: 'fullname', displayName: 'Full Name' } }], sampleData: { contact: [{ lastname: 'Probe' }] } });
+ const first = await p.command(org, spec, { argv: [...DATA, '--sample-data'] });
+ assert.equal(first.thrown, null, first.stderr.slice(-900));
+ assert.equal(first.exitCode, 0, first.stderr.slice(-900));
+ assert.match(first.stderr, /transient error in sample-data — retrying \(attempt 1\/3\)/);
+ assert.equal(refused, 2, 'the sample data was sent by two attempts');
+ // Both attempts used the same ids: one create per root, at the id the binding store holds.
+ assert.deepEqual(rootCreates(org).sort(), ['POST /customapis', 'POST /duplicaterules', 'POST /environmentvariabledefinitions', 'POST /environmentvariabledefinitions']);
+ // The retried attempt is the one reported: it found every row unchanged at the id the first attempt created it with.
+ const bound = first.payload.created.configuration.unchanged;
+ assert.equal(bound.length, 4, JSON.stringify(first.payload.created.configuration));
+ const idOf = (kind, key) => bound.find((b) => b.kind === kind && b.key === key).id;
+ assert.equal(org.rows('customapis')[0].customapiid, idOf('customApi', 'contoso_Calc'));
+ assert.equal(org.rows('duplicaterules')[0].duplicateruleid, idOf('duplicateRule', 'email'));
+ const ids = PROTECTED_ROWS.map((set) => org.rows(set).map((r) => JSON.stringify(r)).sort());
+
+ const mark = org.requests.length;
+ const again = await p.command(org, spec);
+ assert.equal(again.thrown, null, again.thrown && again.thrown.message);
+ assert.equal(again.exitCode, 0, again.stderr.slice(-900));
+ assert.deepEqual(org.writes(mark), [], 'the reopened folder found every row at its bound id');
+ assert.deepEqual(PROTECTED_ROWS.map((set) => org.rows(set).map((r) => JSON.stringify(r)).sort()), ids);
+ assert.equal(new Set(p.pids).size, 2, 'two OS processes');
+ assert.ok(!p.pids.includes(process.pid));
+ assert.deepEqual(org.unexpected, []);
+});
+
+test('protected configuration in fresh processes: a create whose answer was lost is completed, approved and bound across four processes, and sent once', async () => {
+ const p = processCommands();
+ let org = null;
+ let sends = 0;
+ let replaying = false;
+ org = commandOrg({ intercept: async (req) => {
+ if (replaying || req.method !== 'POST' || req.path.split('?')[0] !== '/customapis') return undefined;
+ sends += 1;
+ if (sends > 1) return undefined;
+ replaying = true;
+ try {
+ await org.request({ url: `${org.origin}/api/data/v9.0${req.path}`, method: 'POST', headers: req.headers, body: JSON.stringify(req.body) });
+ } finally {
+ replaying = false;
+ }
+ return { statusCode: 503, body: { error: { code: '0x80040216', message: 'the answer was lost' } } };
+ } });
+ const first = await p.command(org, protectedSpec());
+ assert.match(String(first.thrown && first.thrown.message), /customApi contoso_Calc \(create-outcome-unknown\)/);
+ assert.equal(sends, 1);
+
+ let mark = org.requests.length;
+ const blocked = await p.command(org, protectedSpec());
+ assert.equal(blocked.thrown && blocked.thrown.code, 'create-completion-required', blocked.thrown && blocked.thrown.message);
+ assert.deepEqual(org.writes(mark), []);
+
+ // The maker completes the row's solution membership, reading the members the earlier process stored on disk.
+ const store = openManagedBindings({ workspaceDir: path.join(p.appDir, '.maker-workspace'), environment: org.origin, appUniqueName: 'contoso_configprobe', solutionUniqueName: 'ContosoSol' });
+ const inSolution = new Set(org.rows('solutioncomponents').map((c) => c.objectid));
+ for (const m of store.readGroup('customApi', 'contoso_calc').pending.rowProtocol.completion.members) {
+ if (inSolution.has(m.id)) continue;
+ await org.request({ url: `${org.origin}/api/data/v9.2/AddSolutionComponent`, method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ SolutionUniqueName: 'ContosoSol', ComponentId: m.id, ComponentType: m.componentType, AddRequiredComponents: false }) });
+ }
+
+ mark = org.requests.length;
+ const asked = await p.command(org, protectedSpec());
+ assert.equal(asked.thrown && asked.thrown.code, 'create-ownership-required', asked.thrown && asked.thrown.message);
+ assert.deepEqual(org.writes(mark), []);
+ const tokens = JSON.parse(`[${/given after checking those rows are yours: (.*)\.$/.exec(asked.thrown.message)[1]}]`);
+ assert.equal(tokens.length, 3);
+
+ const done = await p.command(org, protectedSpec(), { argv: [...DATA, ...authorize(tokens)] });
+ assert.equal(done.thrown, null, done.thrown && done.thrown.message);
+ assert.equal(done.exitCode, 0, done.stderr.slice(-900));
+ assert.equal(sends, 1, 'the Custom API was sent once, by the first process');
+ assert.equal(org.rows('customapis').length, 1);
+ assert.equal(new Set(p.pids).size, 4, 'four OS processes');
+ assert.deepEqual(org.unexpected, []);
+});
+
+// A protected Custom API whose implementation (a plug-in type) was registered outside the plugin, as an App Spec cannot declare
+// one (configuration-artifacts.js refuses `pluginTypeId`). The build never writes the implementation; a bound row keeps the exact
+// plug-in type its fresh read found, and the edit is proved only while the row still holds that one.
+const PLUGIN_TYPE = '00000000-0000-4000-8000-0000000000aa';
+const OTHER_PLUGIN_TYPE = '00000000-0000-4000-8000-0000000000bb';
+function apiSpec(over = {}) {
+ return { ...makeSpec({ configuration: false }), solution: makeSpec().solution, configurationIdentity: 'stable-v1',
+ customApis: [structuredClone(CONFIGURATION_FIELDS.customApis[0])], ...over };
+}
+const withApi = (spec, change) => ({ ...spec, customApis: [{ ...spec.customApis[0], ...change }] });
+const withRequest = (spec, uniqueName) => withApi(spec, { requestParameters: [...spec.customApis[0].requestParameters, { uniqueName, type: 'integer' }] });
+function apiGroup(base) {
+ const store = openManagedBindings({ workspaceDir: path.join(base.appDir, '.maker-workspace'), environment: base.org.origin, appUniqueName: 'contoso_configprobe', solutionUniqueName: 'ContosoSol' });
+ const group = store.readGroup('customApi', 'contoso_calc');
+ return { committed: !!group.committed, pending: !!group.pending };
+}
+function succeeded(out, what) {
+ assert.equal(out.thrown && out.thrown.message, undefined, what);
+ assert.equal(out.exitCode, 0, `${what}: ${out.stderr.slice(-900)}`);
+}
+// No write since `mark` names the implementation, in any shape (a lookup column or a bind).
+const writesImplementation = (org, mark) => org.requests.slice(mark).some((r) => r.method !== 'GET' && /plugintype/i.test(JSON.stringify(r.body || {})));
+
+test('protected configuration through the build command: a Custom API with a registered implementation takes a supported root edit, keeps that implementation, and the rerun sends nothing', async () => {
+ const spec = apiSpec();
+ const out = await runCommand(spec);
+ succeeded(out, 'the create');
+ const api = out.org.rows('customapis')[0];
+ api._plugintypeid_value = PLUGIN_TYPE;
+ let mark = out.org.requests.length;
+ succeeded(await runAgain(spec, out), 'an unchanged build over the implemented API');
+ assert.deepEqual(out.org.writes(mark), []);
+
+ const edited = withApi(spec, { displayName: 'Calculator' });
+ mark = out.org.requests.length;
+ succeeded(await runAgain(edited, out), 'the root edit');
+ assert.deepEqual(out.org.writes(mark), [`PATCH /customapis(${api.customapiid})`]);
+ assert.equal(api.displayname, 'Calculator');
+ assert.equal(api._plugintypeid_value, PLUGIN_TYPE, 'the implementation is kept');
+ assert.equal(writesImplementation(out.org, mark), false, 'the implementation is never written');
+ assert.deepEqual(apiGroup(out), { committed: true, pending: false });
+
+ // A new process over the same folder: the edit is bound, so nothing is sent again.
+ mark = out.org.requests.length;
+ succeeded(await runAgain(edited, out), 'the rerun');
+ assert.deepEqual(out.org.writes(mark), []);
+ assert.deepEqual(out.org.unexpected, []);
+});
+
+test('protected configuration through the build command: a Custom API with a registered implementation takes a new-child edit and keeps that implementation', async () => {
+ const spec = apiSpec();
+ const out = await runCommand(spec);
+ succeeded(out, 'the create');
+ const api = out.org.rows('customapis')[0];
+ api._plugintypeid_value = PLUGIN_TYPE;
+ const edited = withRequest(spec, 'B');
+ let mark = out.org.requests.length;
+ succeeded(await runAgain(edited, out), 'the new-child edit');
+ assert.deepEqual(out.org.writes(mark), ['POST /customapirequestparameters', 'POST /AddSolutionComponent']);
+ assert.deepEqual(out.org.rows('customapirequestparameters').map((r) => r.uniquename).sort(), ['A', 'B']);
+ assert.equal(api._plugintypeid_value, PLUGIN_TYPE);
+ assert.equal(writesImplementation(out.org, mark), false);
+ assert.deepEqual(apiGroup(out), { committed: true, pending: false });
+ mark = out.org.requests.length;
+ succeeded(await runAgain(edited, out), 'the rerun');
+ assert.deepEqual(out.org.writes(mark), []);
+ assert.deepEqual(out.org.unexpected, []);
+});
+
+test('protected configuration through the build command: an implementation replaced or removed while an edit is written is refused, and the next build sends nothing for it', async () => {
+ for (const [what, during] of [['replaced', OTHER_PLUGIN_TYPE], ['removed', null]]) {
+ let hook = null;
+ const org = commandOrg({ intercept: (req) => (hook ? hook(req) : undefined) });
+ const spec = apiSpec();
+ const out = await runCommand(spec, { org });
+ succeeded(out, `${what}: the create`);
+ const api = org.rows('customapis')[0];
+ api._plugintypeid_value = PLUGIN_TYPE;
+ // Someone else changes the registration as the edit's PATCH lands: the row the edit leaves is not the one it planned.
+ hook = (req) => {
+ if (req.method === 'PATCH' && /^\/customapis\(/.test(req.path)) api._plugintypeid_value = during;
+ return undefined;
+ };
+ const edited = withApi(spec, { displayName: 'Calculator' });
+ let mark = org.requests.length;
+ const changed = await runAgain(edited, out);
+ assert.notEqual(changed.exitCode, 0, what);
+ assert.match(String(changed.thrown && changed.thrown.message), /create-identity-conflict/, what);
+ assert.deepEqual(org.writes(mark), [`PATCH /customapis(${api.customapiid})`], `${what}: sent once`);
+ assert.deepEqual(apiGroup(out), { committed: true, pending: true }, `${what}: the edit stays pending`);
+ hook = null;
+ mark = org.requests.length;
+ const again = await runAgain(edited, out);
+ assert.equal(again.thrown && again.thrown.code, 'create-identity-conflict', `${what}: ${again.thrown && again.thrown.message}`);
+ assert.deepEqual(org.writes(mark), [], `${what}: nothing is sent again`);
+ assert.equal(api._plugintypeid_value, during, `${what}: the implementation is left as it was changed`);
+ assert.deepEqual(org.unexpected, []);
+ }
+});
+
+test('protected configuration through the build command: a first create that reads back with an implementation is still not proved', async () => {
+ let org = null;
+ // The plug-in type appears on the row right after the create lands, before the build reads it back.
+ org = commandOrg({ intercept: (req) => {
+ const row = org.rows('customapis')[0];
+ if (row && req.method === 'GET') row._plugintypeid_value = PLUGIN_TYPE;
+ return undefined;
+ } });
+ const out = await runCommand(apiSpec(), { org });
+ assert.match(String(out.thrown && out.thrown.message), /create-identity-conflict/);
+ assert.deepEqual(rootCreates(org), ['POST /customapis']);
+ assert.deepEqual(apiGroup(out), { committed: false, pending: true });
+ assert.deepEqual(org.unexpected, []);
+});
+
+test('protected configuration through the build command: the same root edit of an API without an implementation, and of an implemented API without the opt-in, is applied', async () => {
+ for (const protectedMode of [true, false]) {
+ const spec = apiSpec();
+ if (!protectedMode) delete spec.configurationIdentity;
+ const out = await runCommand(spec);
+ succeeded(out, `opt-in ${protectedMode}: the create`);
+ const api = out.org.rows('customapis')[0];
+ if (!protectedMode) api._plugintypeid_value = PLUGIN_TYPE;
+ const mark = out.org.requests.length;
+ succeeded(await runAgain(withApi(spec, { displayName: 'Calculator' }), out), `opt-in ${protectedMode}: the root edit`);
+ assert.deepEqual(out.org.writes(mark), [`PATCH /customapis(${api.customapiid})`]);
+ assert.equal(api.displayname, 'Calculator');
+ assert.equal(api._plugintypeid_value ?? null, protectedMode ? null : PLUGIN_TYPE);
+ assert.deepEqual(out.org.unexpected, []);
+ }
+});
+
+// A protected item with no binding yet is a first create at its derived ids. Its exact-id read and its complete namesake query run
+// in the build's read-only preflight, so a create that cannot be made stops the build before its first write (here the solution
+// version PATCH), not after it.
+test('protected configuration through the build command: a first create whose namesake or derived id is taken stops before the first write', async () => {
+ const versioned = (spec) => ({ ...spec, solution: { ...spec.solution, version: '1.3.0.0' } });
+ const solutionVersion = (org) => org.rows('solutions').find((s) => s.uniquename === 'ContosoSol').version;
+
+ // Opting in over an API the build made without the opt-in: a namesake at another id.
+ const plain = apiSpec();
+ delete plain.configurationIdentity;
+ const made = await runCommand(plain);
+ succeeded(made, 'the ordinary create');
+ for (const argv of [undefined, DATA, CHANGED_ONLY]) {
+ const mark = made.org.requests.length;
+ const stopped = await runCommand(versioned(apiSpec()), { org: made.org, appDir: made.appDir, ...(argv ? { argv } : {}) });
+ const label = argv ? argv.join(' ') : 'default';
+ assert.equal(stopped.thrown && stopped.thrown.code, 'create-identity-conflict', `${label}: ${stopped.thrown && stopped.thrown.message}`);
+ assert.equal(stopped.thrown.phase, 'preflight', label);
+ assert.match(stopped.thrown.message, /customApi contoso_calc/, label);
+ assert.notEqual(stopped.exitCode, 0, label);
+ assert.deepEqual(made.org.writes(mark), [], `${label}: nothing is written`);
+ }
+ assert.equal(solutionVersion(made.org), '1.2.0.0');
+ assert.deepEqual(made.org.unexpected, []);
+
+ // The derived id taken by a row no binding of this folder holds (the same App Spec built from another folder).
+ const first = await runCommand(apiSpec());
+ succeeded(first, 'the protected create');
+ const elsewhere = path.join(makeTempDir('config-command-'), 'app');
+ const mark = first.org.requests.length;
+ const taken = await runCommand(versioned(apiSpec()), { org: first.org, appDir: elsewhere });
+ assert.equal(taken.thrown && taken.thrown.code, 'create-identity-conflict', taken.thrown && taken.thrown.message);
+ assert.equal(taken.thrown.phase, 'preflight');
+ assert.deepEqual(first.org.writes(mark), []);
+ assert.equal(solutionVersion(first.org), '1.2.0.0');
+ assert.deepEqual(first.org.unexpected, []);
+});
+
+test('protected configuration through the build command: a first create whose namesake query cannot be completed stops before the first write', async () => {
+ let failing = false;
+ const org = commandOrg({ intercept: (req) => (failing && req.method === 'GET' && /^\/customapis\?/.test(req.path) && /\$filter=uniquename/.test(decodeURIComponent(req.path))
+ ? { statusCode: 500, body: { error: { code: '0x80040216', message: 'unavailable' } } } : undefined) });
+ const solutionVersion = () => org.rows('solutions').find((s) => s.uniquename === 'ContosoSol').version;
+ const base = await runCommand({ ...makeSpec({ configuration: false }), solution: makeSpec().solution }, { org });
+ succeeded(base, 'the solution');
+ failing = true;
+ const mark = org.requests.length;
+ const stopped = await runCommand(apiSpec({ solution: { ...makeSpec().solution, version: '1.3.0.0' } }), { org, appDir: base.appDir });
+ assert.equal(stopped.thrown && stopped.thrown.code, 'create-identity-unverified', stopped.thrown && stopped.thrown.message);
+ assert.equal(stopped.thrown.phase, 'preflight');
+ assert.deepEqual(org.writes(mark), []);
+ assert.equal(solutionVersion(), '1.2.0.0');
+ assert.equal(org.rows('customapis').length, 0);
+ assert.deepEqual(org.unexpected, []);
+});
+
+// Two answers a live environment gives that a protected build must take as they are (fake-config-org.js liveRowShape): the platform
+// stores its create default in a connection reference's `promptingbehavior` (0) although the create never sends it, and answers a
+// duplicate rule without `@odata.etag`.
+const liveOrg = () => commandOrg({ liveRowShape: true });
+const noUnexpectedError = (out, what) => assert.ok(!/UNEXPECTED_ERROR/.test(`${out.stderr} ${out.stdout || ''} ${JSON.stringify(out.payload || null)}`), `${what}: ${out.stderr.slice(-900)}`);
+
+test('protected configuration through the build command: a connection reference the platform fills with its create default is created, bound and rebuilt with no write', async () => {
+ const spec = { ...makeSpec({ configuration: false }), solution: makeSpec().solution, configurationIdentity: 'stable-v1',
+ connectionReferences: [{ logicalName: 'contoso_sp', connectorId: SP }] };
+ const org = liveOrg();
+ const out = await runCommand(spec, { org });
+ succeeded(out, 'the create');
+ noUnexpectedError(out, 'the create');
+ const [row] = org.rows('connectionreferences');
+ assert.equal(row.promptingbehavior, 0, 'the platform filled its create default');
+ assert.deepEqual(out.payload.created.configuration.managedBindings.map((b) => `${b.kind}:${b.key}:${b.origin}:${b.id}`),
+ [`connectionReference:contoso_sp:created:${row.connectionreferenceid}`]);
+ assert.ok(!org.requests.some((r) => r.method !== 'GET' && /promptingbehavior/i.test(JSON.stringify(r.body || {}))), 'the column is never sent');
+ const mark = org.requests.length;
+ succeeded(await runAgain(spec, out), 'the unchanged rebuild');
+ assert.deepEqual(org.writes(mark), []);
+ assert.deepEqual(org.unexpected, []);
+
+ // Any other value there, found as the create is read back, was put by someone else: the row is not proved the build's.
+ let other = null;
+ other = commandOrg({ liveRowShape: true, intercept: (req) => {
+ const made = other.rows('connectionreferences')[0];
+ if (made && req.method === 'GET') made.promptingbehavior = 1;
+ return undefined;
+ } });
+ const stopped = await runCommand(spec, { org: other });
+ assert.notEqual(stopped.exitCode, 0);
+ assert.match(String(stopped.thrown && stopped.thrown.message), /connectionReference contoso_sp \(create-identity-conflict\)/);
+ assert.deepEqual(other.unexpected, []);
+});
+
+test('protected configuration through the build command: a duplicate rule answered without a row version is created, verified and rebuilt with no write, and a change to it is unsupported', async () => {
+ const spec = { ...makeSpec({ configuration: false }), solution: makeSpec().solution, configurationIdentity: 'stable-v1',
+ duplicateDetectionRules: structuredClone(CONFIGURATION_FIELDS.duplicateDetectionRules) };
+ const org = liveOrg();
+ const out = await runCommand(spec, { org, argv: [...DATA, '--verify'] });
+ succeeded(out, 'the create');
+ noUnexpectedError(out, 'the create');
+ assert.doesNotMatch(out.stderr, /✗ configuration/, out.stderr.slice(-900));
+ assert.match(out.stderr, /✓ verify PASS/, 'the build verified the rule');
+ const [rule] = org.rows('duplicaterules');
+ assert.deepEqual([rule.statecode, rule.statuscode], [1, 2], 'published once');
+ let mark = org.requests.length;
+ const again = await runAgain(spec, out);
+ succeeded(again, 'the unchanged rebuild');
+ noUnexpectedError(again, 'the unchanged rebuild');
+ assert.deepEqual(org.writes(mark), [], 'never published again');
+ // The build's own verify checks the bound rule at its id, through the same plan, and finds it as made.
+ mark = org.requests.length;
+ const verified = await runAgain(spec, out, [...DATA, '--verify']);
+ succeeded(verified, 'the verified rebuild');
+ noUnexpectedError(verified, 'the verified rebuild');
+ assert.doesNotMatch(verified.stderr, /✗ configuration/, verified.stderr.slice(-900));
+ assert.match(verified.stderr, /✓ verify PASS/);
+ assert.deepEqual(org.writes(mark), []);
+
+ for (const [what, change] of [
+ ['a field', (s) => { s.duplicateDetectionRules[0].name = 'Contacts with the same email'; }],
+ ['a condition', (s) => { s.duplicateDetectionRules[0].conditions[0].match = 'firstCharacters'; s.duplicateDetectionRules[0].conditions[0].characters = 3; }],
+ ]) {
+ const edited = structuredClone(spec);
+ change(edited);
+ mark = org.requests.length;
+ const refused = await runAgain(edited, out);
+ assert.equal(refused.thrown && refused.thrown.code, 'configuration-edit-unsupported', `${what}: ${refused.thrown && refused.thrown.message}`);
+ assert.equal(refused.thrown.phase, 'preflight', what);
+ assert.deepEqual(org.writes(mark), [], what);
+ }
+ assert.deepEqual(org.unexpected, []);
+});
+
+// A Custom API label edit is refused by the SDK before anything is sent when the environment has more than one language. The
+// refused edit leaves nothing pending, so the build that follows — the earlier declaration, another edit or the same one — is
+// judged on its own.
+test('protected configuration through the build command: a label edit refused before any send leaves nothing pending, so the next declaration is built', async () => {
+ const org = commandOrg({ languages: [1033, 1036] });
+ const spec = apiSpec();
+ const out = await runCommand(spec, { org });
+ succeeded(out, 'the create');
+ const labelled = withApi(spec, { requestParameters: [{ ...spec.customApis[0].requestParameters[0], displayName: 'Alpha' }] });
+ const refused = async (what) => {
+ const mark = org.requests.length;
+ const r = await runAgain(labelled, out);
+ assert.notEqual(r.exitCode, 0, what);
+ assert.match(String(r.thrown && r.thrown.message), /CUSTOM_API_LABELS_UNSUPPORTED/, `${what}: ${r.thrown && r.thrown.message}`);
+ assert.doesNotMatch(String(r.thrown && r.thrown.message), /another declaration/, what);
+ assert.deepEqual(org.writes(mark), [], `${what}: nothing is sent`);
+ assert.deepEqual(apiGroup(out), { committed: true, pending: false }, `${what}: nothing is left pending`);
+ };
+ await refused('the label edit');
+
+ let mark = org.requests.length;
+ succeeded(await runAgain(spec, out), 'the earlier declaration');
+ assert.deepEqual(org.writes(mark), []);
+
+ await refused('the label edit again');
+ const extended = withRequest(spec, 'B');
+ mark = org.requests.length;
+ succeeded(await runAgain(extended, out), 'another declaration');
+ assert.deepEqual(org.writes(mark), ['POST /customapirequestparameters', 'POST /AddSolutionComponent']);
+ assert.deepEqual(apiGroup(out), { committed: true, pending: false });
+ assert.equal(org.rows('customapirequestparameters').find((p) => p.uniquename === 'A').displayname, 'A', 'the refused label was never written');
+ assert.deepEqual(org.unexpected, []);
+});
+
+// A maker may change a bound reference's prompting behaviour in the portal. The build never writes that column, and an
+// edit of the row is planned over the value its fresh base read found there: the edit completes and keeps it, a rerun
+// sends nothing, and a value changed again while the edit is written leaves the edit unfinished, never proved.
+test('protected configuration through the build command: a bound connection reference whose prompting behaviour was changed outside the plugin takes a supported edit and keeps that value', async () => {
+ const spec = { ...makeSpec({ configuration: false }), solution: makeSpec().solution, configurationIdentity: 'stable-v1',
+ connectionReferences: [{ logicalName: 'contoso_sp', connectorId: SP }] };
+ const pending = (out) => {
+ const store = openManagedBindings({ workspaceDir: path.join(out.appDir, '.maker-workspace'), environment: out.org.origin,
+ appUniqueName: spec.app.uniqueName, solutionUniqueName: 'ContosoSol' });
+ return !!store.readGroup('connectionReference', 'contoso_sp').pending;
+ };
+ const named = (name) => ({ ...spec, connectionReferences: [{ ...spec.connectionReferences[0], name }] });
+
+ const out = await runCommand(spec, { org: liveOrg() });
+ succeeded(out, 'the create');
+ const [row] = out.org.rows('connectionreferences');
+ row.promptingbehavior = 1;
+ let mark = out.org.requests.length;
+ succeeded(await runAgain(spec, out), 'the unchanged rebuild');
+ assert.deepEqual(out.org.writes(mark), []);
+
+ mark = out.org.requests.length;
+ succeeded(await runAgain(named('Reviewed reference'), out), 'the name edit');
+ assert.equal(out.org.writes(mark).length, 1, JSON.stringify(out.org.writes(mark)));
+ assert.equal(row.connectionreferencedisplayname, 'Reviewed reference');
+ assert.equal(row.promptingbehavior, 1, 'the value set outside the plugin is kept');
+ assert.equal(pending(out), false, 'the edit is complete');
+ assert.ok(!out.org.requests.slice(mark).some((r) => r.method !== 'GET' && /promptingbehavior/i.test(JSON.stringify(r.body || {}))), 'the column is never sent');
+ mark = out.org.requests.length;
+ succeeded(await runAgain(named('Reviewed reference'), out), 'the rerun');
+ assert.deepEqual(out.org.writes(mark), []);
+ // Back at the platform default, an edit is planned over that state as well.
+ row.promptingbehavior = null;
+ mark = out.org.requests.length;
+ succeeded(await runAgain(named('Third name'), out), 'the edit over an empty value');
+ assert.equal(out.org.writes(mark).length, 1);
+ assert.equal(pending(out), false);
+ assert.deepEqual(out.org.unexpected, []);
+
+ // Changed again while the edit is written: the read-back does not hold what the edit was planned over.
+ let drifted = null;
+ drifted = commandOrg({ liveRowShape: true, intercept: (req) => {
+ if (req.method === 'PATCH' && /^\/connectionreferences\(/.test(req.path)) drifted.rows('connectionreferences')[0].promptingbehavior = 2;
+ return undefined;
+ } });
+ const made = await runCommand(spec, { org: drifted });
+ succeeded(made, 'the second create');
+ drifted.rows('connectionreferences')[0].promptingbehavior = 1;
+ const stopped = await runAgain(named('Reviewed reference'), made);
+ assert.notEqual(stopped.exitCode, 0);
+ assert.match(String(stopped.thrown && stopped.thrown.message), /connectionReference contoso_sp \(create-identity-conflict\)/);
+ assert.equal(pending(made), true, 'the edit is not proved');
+ mark = drifted.requests.length;
+ const next = await runAgain(named('Reviewed reference'), made);
+ assert.notEqual(next.exitCode, 0);
+ assert.deepEqual(drifted.writes(mark), [], 'the next build sends nothing for it');
+ assert.deepEqual(drifted.unexpected, []);
});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/configuration-create-bindings.test.js b/plugins/model-apps/scripts/tests/configuration-create-bindings.test.js
new file mode 100644
index 000000000..61b7ae9a8
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/configuration-create-bindings.test.js
@@ -0,0 +1,938 @@
+'use strict';
+// The protected create driver of the configuration families (lib/configuration-create-bindings.js), which the build uses
+// under the opt-in: its plan, its exact and namesake reads, its classifier of the SDK's own requests, and one full create set
+// through the real SDK, the real send-once gate and the real binding store against the fake org.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('fs');
+const path = require('path');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { createConfigOrg } = require('./helpers/fake-config-org.js');
+const { createAzHttpClient } = require('../lib/sdk-http-client.js');
+const { createMakerSdk, createNodeWorkspaceStorage } = require('../lib/maker-sdk.js');
+const { configurationSendOnce } = require('../lib/configuration-transport.js');
+const { createDeferredManagedCreateGate } = require('../lib/managed-create-transport.js');
+const { CODES, createManagedCreateContext } = require('../lib/managed-create-context.js');
+const { openManagedBindings } = require('../lib/managed-bindings.js');
+const A = require('../lib/configuration-artifacts.js');
+const B = require('../lib/configuration-create-bindings.js');
+
+const SOL = 'ContosoSol';
+const SP = '/providers/Microsoft.PowerApps/apis/shared_sharepointonline';
+const VALUE = 'private-value-7f3a';
+const CONNECTION = 'private-connection-9c1e';
+const OTHER = '77777777-7777-4777-8777-777777777777';
+const spec = (over = {}) => ({
+ minimumPluginVersion: '2.21.0', solution: { uniqueName: SOL, publisherPrefix: 'contoso' },
+ environmentVariables: [{ schemaName: 'contoso_ApiBase', type: 'string', defaultValue: 'x' }],
+ connectionReferences: [{ logicalName: 'contoso_sp', connectorId: SP }],
+ customApis: [{ uniqueName: 'contoso_Calc', isFunction: true, requestParameters: [{ uniqueName: 'A', type: 'integer' }], responseProperties: [{ uniqueName: 'R', type: 'string' }] }],
+ duplicateDetectionRules: [{ key: 'email', name: 'Same email', entity: 'contact', conditions: [{ key: 'e', column: 'emailaddress1', match: 'exact' }] }],
+ ...over,
+});
+const DEPLOY = { EnvironmentVariables: [{ SchemaName: 'contoso_ApiBase', Value: VALUE }], ConnectionReferences: [{ LogicalName: 'contoso_sp', ConnectionId: CONNECTION }] };
+const TYPES = { connectionreference: 10132, customapi: 10133, duplicaterule: 4414, customapirequestparameter: 10134, customapiresponseproperty: 10135, duplicaterulecondition: 4416 };
+const ALL = [['environmentVariable', 'contoso_ApiBase'], ['connectionReference', 'contoso_sp'], ['customApi', 'contoso_Calc'], ['duplicateRule', 'email']];
+
+function planned(kind, key, over = {}) {
+ const s = over.spec || spec();
+ return B.planOf(s, { kind, key, bindings: A.readDeploymentBindings(DEPLOY, s), solution: SOL, componentTypes: TYPES, ...over, spec: undefined });
+}
+const rowOf = (p, kind) => p.rows.find((r) => r.kind === kind);
+
+function orgOf(opts = {}) {
+ return createConfigOrg({ tables: [{ logicalName: 'contact', attributes: ['emailaddress1', 'lastname'] }], solution: { uniqueName: SOL, version: '1.0.0.0', prefix: 'contoso' }, ...opts });
+}
+async function sdkOf(org, gate) {
+ const httpClient = createAzHttpClient(org.origin, { getToken: () => 'test-token-0123456789abcdef', request: org.request, sleep: async () => {}, sendOnce: configurationSendOnce, workflowEffectGate: gate });
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(makeTempDir('cfg-create-sdk-')), instanceUrl: org.origin, httpClient, solutionUniqueName: SOL });
+ await sdk.initWorkspace();
+ return sdk;
+}
+// A seed row, written straight to the fake org (no SDK, no gate): a namesake someone else made.
+async function seed(org, set, body) {
+ const res = await org.request({ url: `${org.origin}/api/data/v9.2/${set}`, method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
+ assert.ok(res.statusCode < 300, `seed ${set}: ${res.statusCode}`);
+}
+// Every mutation the real SDK sends to push `p` (or `artifact` in its place), as the gate is asked about it (the body is
+// the JSON text it sends). `sent` keeps capturing, so a later edit pushed through `sdk` is captured too.
+async function wireOf(p, { artifact = B.artifactFor(p), org = orgOf() } = {}) {
+ const sent = [];
+ const sdk = await sdkOf(org, { screen(req) { if (req.method !== 'GET') sent.push({ ...req, headers: { ...req.headers } }); return null; } });
+ await sdk.createArtifact(p.kind, artifact);
+ const result = await sdk.pushArtifact(p.kind, p.plan.rows[0].id);
+ for (const m of p.plan.members) {
+ await sdk.dataverse.post('/AddSolutionComponent', { ComponentId: m.id, ComponentType: m.componentType, SolutionUniqueName: SOL, AddRequiredComponents: false });
+ }
+ return { sent, result, org, sdk };
+}
+const withBody = (req, edit) => {
+ const b = JSON.parse(req.body);
+ edit(b);
+ return { ...req, body: JSON.stringify(b) };
+};
+const thrown = (fn) => { try { fn(); } catch (e) { return e; } return null; };
+
+// A reader over canned answers: `routes` is [[prefix-or-regexp, answer | (path) => answer]]; an unrouted read is a 500.
+function reader(routes, { absolute } = {}) {
+ const answerFor = (p) => {
+ for (const [match, a] of routes) {
+ if (typeof match === 'string' ? p.startsWith(match) : match.test(p)) return typeof a === 'function' ? a(p) : a;
+ }
+ return { status: 500, body: { error: { code: '0x80040216' } } };
+ };
+ return { get: async (p) => answerFor(p), getAbsolute: async (u) => (absolute ? absolute(u) : answerFor(u)) };
+}
+const ok = (value, extra = {}) => ({ status: 200, body: { value, ...extra } });
+
+// The fresh base read of every planned row that exists now, as a bound plan is prepared from it.
+async function basesOf(dv, p) {
+ const bases = new Map();
+ for (const r of p.plan.rows) {
+ const read = await B.readConfigurationRow(dv, r.kind, r.id);
+ if (read.state === 'present') bases.set(r.id, read);
+ }
+ return bases;
+}
+// The plan of an edit of `first` once it exists: its root bound, its existing children bound, each from a fresh read.
+async function rebound(dv, first, over = {}) {
+ const bases = await basesOf(dv, first);
+ const boundSlots = first.rows.filter((r) => r.slot !== null && bases.has(r.id)).map((r) => r.slot);
+ return planned(first.kind, first.key, { boundIdOf: (kind) => (kind === first.kind ? first.plan.rows[0].id : undefined), boundSlots, bases, ...over });
+}
+// The requests the real SDK sends to push an edit of an artifact it pushed before: `ops` are its element updates.
+async function pushEdit(w, kind, id, ops) {
+ await w.sdk.fetchArtifact(kind, id, { overwrite: true });
+ for (const [pointer, value] of ops) await w.sdk.updateElement(kind, id, pointer, value);
+ w.sent.length = 0;
+ const result = await w.sdk.pushArtifact(kind, id);
+ return { result, sent: [...w.sent] };
+}
+// The change-set constituents of a $batch as the SDK renders it (CRLF lines; the boundaries differ per request):
+// --changeset_<id>\r\nContent-Type: application/http\r\nContent-Transfer-Encoding: binary\r\nContent-ID: 1\r\n\r\n
+// PATCH https://contoso.crm.dynamics.com/api/data/v9.0/customapis(<id>)?$select=customapiid HTTP/1.1\r\n
+// MSCRM.SolutionUniqueName: ContosoSol\r\nIf-Match: W/"16"\r\nPrefer: return=representation\r\n\r\n{"isprivate":false}\r\n
+function constituentsOf(req) {
+ return String(req.body).split(/--changeset_[\w-]+/).filter((c) => c.includes('application/http')).map((chunk) => {
+ const [, head, ...rest] = chunk.split('\r\n\r\n');
+ const [line, ...headerLines] = head.split('\r\n');
+ const [, method, url] = /^(\w+) (\S+) HTTP\/1\.1$/.exec(line);
+ const headers = Object.fromEntries(headerLines.map((h) => [h.slice(0, h.indexOf(':')), h.slice(h.indexOf(':') + 1).trim()]));
+ return { method, url, headers, body: rest.join('\r\n\r\n').replace(/\r\n$/, '') };
+ });
+}
+
+test('planOf: one artifact\'s rows at the derived ids, members of its solution, no private input anywhere in the plan', () => {
+ const ev = planned('environmentVariable', 'contoso_ApiBase');
+ assert.deepEqual(ev.plan.rows.map((r) => [r.kind, r.mode, r.sensitiveInput]), [['environmentVariable', 'create', false], ['environmentVariableValue', 'create', true]]);
+ assert.equal(ev.plan.rows[1].parentId, ev.plan.rows[0].id);
+ assert.deepEqual(ev.plan.members, [{ kind: 'environmentVariable', id: ev.plan.rows[0].id, componentType: 380 }], 'a value row is never a member');
+ const rule = planned('duplicateRule', 'email');
+ assert.equal(rule.plan.ruleState, 'published');
+ assert.deepEqual(rule.plan.effects.map((e) => e.kind), ['membership', 'membership', 'rule-state']);
+ const cr = planned('connectionReference', 'contoso_sp');
+ for (const p of [ev, cr]) {
+ const text = JSON.stringify(p);
+ assert.ok(!text.includes(VALUE) && !text.includes(CONNECTION), 'the planned object carries no private input');
+ }
+ assert.equal(B.artifactFor(ev).currentValue.value, VALUE, 'only the SDK artifact carries it');
+ assert.equal(B.artifactFor(cr).connectionId, CONNECTION);
+ assert.ok(Object.isFrozen(ev.rows[0].expected));
+ assert.deepEqual(planned('customApi', 'contoso_Calc'), planned('customApi', 'contoso_Calc'), 'the plan is deterministic');
+});
+
+test('planOf: membership needs the component types; a restricted solution plans none', () => {
+ assert.throws(() => planned('customApi', 'contoso_Calc', { componentTypes: undefined }), /component type of customapi/);
+ const def = planned('customApi', 'contoso_Calc', { componentTypes: undefined, solution: 'Default' });
+ assert.deepEqual(def.plan.members, []);
+ assert.deepEqual(def.plan.effects, []);
+});
+
+test('readConfigurationRow: absent only on 404 0x80040217; any other failure or a malformed answer is unknown', async () => {
+ const p = planned('customApi', 'contoso_Calc');
+ const { sdk } = await wireOf(p);
+ const id = p.plan.rows[0].id;
+ const real = await sdk.dataverse.get(`/customapis(${id})?$select=${['customapiid', ...Object.keys(B.KINDS.customApi.columns)].join(',')}`);
+ const present = await B.readConfigurationRow(sdk.dataverse, 'customApi', id);
+ assert.equal(present.state, 'present');
+ assert.equal((await B.readConfigurationRow(sdk.dataverse, 'customApi', OTHER)).state, 'absent', 'the fake org answers 404 0x80040217');
+ const cases = [
+ ['403', { status: 403, body: { error: { code: '0x80040220' } } }],
+ ['500', { status: 500, body: {} }],
+ ['404 without the not-found code', { status: 404, body: { error: { code: '0x80060888' } } }],
+ ['a 200 that is not an object', { status: 200, body: '<html>' }],
+ ['another row', { status: 200, body: { ...real.body, customapiid: OTHER } }],
+ ['a selected column left out', { status: 200, body: Object.fromEntries(Object.entries(real.body).filter(([k]) => k !== 'isprivate')) }],
+ ['an option code this build does not know', { status: 200, body: { ...real.body, bindingtype: 9 } }],
+ ];
+ for (const [what, answer] of cases) {
+ assert.equal((await B.readConfigurationRow(reader([['/customapis(', answer]]), 'customApi', id)).state, 'unknown', what);
+ }
+ const threw = { get: async () => { throw Object.assign(new Error('socket'), { statusCode: 404, body: { error: { code: '0x80040217' } } }); } };
+ assert.equal((await B.readConfigurationRow(threw, 'customApi', id)).state, 'absent', 'a thrown 404 0x80040217 is the same absence');
+ assert.equal((await B.readConfigurationRow({ get: async () => { throw new Error('reset'); } }, 'customApi', id)).state, 'unknown');
+});
+
+test('namesake queries follow every page: a namesake on a later page is a conflict; an unfollowable page is unknown', async () => {
+ const p = planned('customApi', 'contoso_Calc');
+ const api = p.plan.rows[0].id;
+ // The planned API exists (as a resumed create would find it) with two request parameters: "X" on page 1, and a
+ // namesake "A" at another id on page 2. A response property "A" is the other direction: never a namesake of a request parameter.
+ const org = orgOf({ pageSize: 1 });
+ await seed(org, 'customapis', {
+ customapiid: api, uniquename: 'contoso_Calc', name: 'contoso_Calc', displayname: 'contoso_Calc', bindingtype: 0, isfunction: true, allowedcustomprocessingsteptype: 0,
+ CustomAPIRequestParameters: [{ customapirequestparameterid: '11111111-0000-4000-8000-000000000001', uniquename: 'X', name: 'X', displayname: 'X', type: 7 },
+ { customapirequestparameterid: OTHER, uniquename: 'a', name: 'a', displayname: 'a', type: 7 }],
+ CustomAPIResponseProperties: [{ customapiresponsepropertyid: '11111111-0000-4000-8000-000000000002', uniquename: 'A', name: 'A', displayname: 'A', type: 10 }],
+ });
+ const sdk = await sdkOf(org, null);
+ const out = await B.readConfigurationConflicts(sdk.dataverse, p);
+ assert.equal(out.state, 'unknown', 'the root at the planned id answers its own namesake query: the reads disagree');
+ const childOnly = out.rows.filter((r) => r.kind !== 'customApi');
+ assert.deepEqual(childOnly.map((r) => [r.kind, r.state, r.ids]), [['customApiRequestParameter', 'conflict', [OTHER]], ['customApiResponseProperty', 'clear', undefined]]);
+ assert.ok(org.requests.some((r) => /\$skiptoken=/.test(r.path)), 'the second page was read');
+
+ const rootQ = '/customapis?';
+ const reqQ = '/customapirequestparameters?';
+ const respQ = '/customapiresponseproperties?';
+ const clearAll = [[rootQ, ok([])], [reqQ, ok([])], [respQ, ok([])]];
+ assert.equal((await B.readConfigurationConflicts(reader(clearAll), p)).state, 'clear');
+ const link = 'https://contoso.crm.dynamics.com/api/data/v9.2/customapis?$skiptoken=1';
+ const cases = [
+ ['an empty first page whose continuation fails', [[rootQ, ok([], { '@odata.nextLink': link })]], () => ({ status: 503, body: {} })],
+ ['a continuation that repeats', [[rootQ, ok([], { '@odata.nextLink': link })]], () => ok([], { '@odata.nextLink': link })],
+ ['a relative continuation', [[rootQ, ok([], { '@odata.nextLink': '/api/data/v9.2/customapis?$skiptoken=1' })]]],
+ ['more records without a link', [[rootQ, ok([], { '@Microsoft.Dynamics.CRM.morerecords': true })]]],
+ ['a page that is not a list', [[rootQ, { status: 200, body: { value: {} } }]]],
+ ];
+ for (const [what, routes, absolute] of cases) {
+ const out2 = await B.readConfigurationConflicts(reader([...routes, ...clearAll], { absolute }), p);
+ assert.deepEqual([out2.state, out2.code], ['unknown', CODES.unverified], what);
+ }
+ const later = await B.readConfigurationConflicts(reader([[rootQ, ok([], { '@odata.nextLink': link })], ...clearAll], { absolute: () => ok([{ customapiid: OTHER, uniquename: 'CONTOSO_calc' }]) }), p);
+ assert.deepEqual([later.state, later.code, later.rows[0].ids], ['conflict', CODES.conflict, [OTHER]], 'a namesake differing only in case, on a later page');
+});
+test('namesake predicates: a rule by name on any table, one value per definition, a condition by what it describes', async () => {
+ const rule = planned('duplicateRule', 'email');
+ const ruleId = rule.plan.rows[0].id;
+ const cond = (over) => ({ duplicateruleconditionid: OTHER, baseattributename: 'EmailAddress1', matchingattributename: 'emailaddress1', operatorcode: 0, operatorparam: null, ignoreblankvalues: false, _regardingobjectid_value: ruleId, ...over });
+ const judge = async (rules, conds) => B.readConfigurationConflicts(reader([['/duplicaterules?', ok(rules)], ['/duplicateruleconditions?', ok(conds)]]), rule);
+ const sameName = await judge([{ duplicateruleid: OTHER, name: 'SAME EMAIL', baseentityname: 'account' }], []);
+ assert.deepEqual([sameName.state, sameName.rows[0].ids], ['conflict', [OTHER]], 'a same-name rule on another table');
+ assert.equal((await judge([], [cond()])).state, 'conflict', 'a condition the declaration describes');
+ assert.equal((await judge([], [cond({ operatorcode: 1, operatorparam: 3 })])).state, 'clear', 'another condition of the rule');
+ assert.equal((await judge([], [cond({ operatorcode: 42 })])).state, 'unknown', 'a condition this build cannot read');
+ assert.equal((await judge([], [cond({ _regardingobjectid_value: OTHER })])).state, 'unknown', 'a row the filter does not hold for');
+ assert.equal((await judge([{ duplicateruleid: OTHER, name: 'Other rule' }], [])).state, 'unknown', 'a name the filter does not hold for');
+ assert.equal((await judge([{ duplicateruleid: ruleId, name: 'Same email' }], [])).state, 'unknown', 'the planned id answering its namesake query');
+ assert.equal((await judge([{ name: 'Same email' }], [])).state, 'unknown', 'a row without an id');
+
+ const ev = planned('environmentVariable', 'contoso_ApiBase');
+ const def = ev.plan.rows[0].id;
+ const evJudge = async (values) => B.readConfigurationConflicts(reader([['/environmentvariabledefinitions?', ok([])], ['/environmentvariablevalues?', ok(values)]]), ev);
+ assert.equal((await evJudge([])).state, 'clear');
+ const v = await evJudge([{ environmentvariablevalueid: OTHER, _environmentvariabledefinitionid_value: def }]);
+ assert.deepEqual([v.state, v.rows[1].ids], ['conflict', [OTHER]], 'any value of the planned definition');
+ assert.equal((await evJudge([{ environmentvariablevalueid: OTHER, _environmentvariabledefinitionid_value: OTHER }])).state, 'unknown');
+});
+
+test('observe: exact reads, the private input compared in memory only, unmodelled columns and unreadable members', async () => {
+ const ev = planned('environmentVariable', 'contoso_ApiBase');
+ const cr = planned('connectionReference', 'contoso_sp');
+ const evWire = await wireOf(ev);
+ const crWire = await wireOf(cr);
+ const exact = await B.observe(evWire.sdk.dataverse, ev);
+ assert.deepEqual(exact.rows.map((r) => [r.kind, r.state, r.projectionSha256 === rowOf(ev, r.kind).expectedSha256, r.privateState]),
+ [['environmentVariable', 'present', true, undefined], ['environmentVariableValue', 'present', true, 'match']]);
+ assert.deepEqual(exact.members, [{ id: ev.plan.rows[0].id, state: 'present' }]);
+ assert.ok(!JSON.stringify(exact).includes(VALUE), 'the observation carries no private input');
+ // The same rows read back with the value masked, hidden or replaced.
+ const over = (dv, set, edit) => ({ ...dv, get: async (p) => { const r = await dv.get(p); return p.startsWith(`/${set}(`) ? { ...r, body: edit({ ...r.body }) } : r; } });
+ const evState = async (edit) => (await B.observe(over(evWire.sdk.dataverse, 'environmentvariablevalues', edit), ev)).rows[1].privateState;
+ assert.equal(await evState((b) => { delete b.value; return b; }), 'masked');
+ assert.equal(await evState((b) => ({ ...b, value: '*****' })), 'masked');
+ assert.equal(await evState((b) => ({ ...b, value: 'someone-else' })), 'mismatch');
+ const crObs = await B.observe(over(crWire.sdk.dataverse, 'connectionreferences', (b) => ({ ...b, promptingbehavior: 1 })), cr);
+ assert.notEqual(crObs.rows[0].projectionSha256, cr.plan.rows[0].expectedSha256, 'a column this build never writes, filled, is a difference');
+ // The platform's own create default there is the row as made; empty is too.
+ for (const filled of [0, null]) {
+ const crDefault = await B.observe(over(crWire.sdk.dataverse, 'connectionreferences', (b) => ({ ...b, promptingbehavior: filled })), cr);
+ assert.equal(crDefault.rows[0].projectionSha256, cr.plan.rows[0].expectedSha256, `promptingbehavior ${filled} read back is the create`);
+ }
+ // Any other value, of any type, is not the row as made.
+ for (const filled of [-1, '0', false]) {
+ const crOther = await B.observe(over(crWire.sdk.dataverse, 'connectionreferences', (b) => ({ ...b, promptingbehavior: filled })), cr);
+ assert.notEqual(crOther.rows[0].projectionSha256, cr.plan.rows[0].expectedSha256, `promptingbehavior ${JSON.stringify(filled)} read back is not the create`);
+ }
+ const noMembers = { ...evWire.sdk.dataverse, get: async (p) => (p.startsWith('/solutioncomponents') ? { status: 500, body: {} } : evWire.sdk.dataverse.get(p)) };
+ assert.deepEqual((await B.observe(noMembers, ev)).members, [{ id: ev.plan.rows[0].id, state: 'unknown' }]);
+ const gone = await B.observe(orgReader(), planned('duplicateRule', 'email'));
+ assert.equal(gone.ruleState, 'unpublished', 'an absent rule is no published rule');
+ assert.ok(gone.rows.every((r) => r.state === 'absent'));
+});
+const orgReader = () => ({ get: async () => ({ status: 404, body: { error: { code: '0x80040217' } } }) });
+test('the classifier names every request the real SDK sends for a planned push, with a sealed projection and no private input', async () => {
+ for (const [kind, key] of ALL) {
+ const p = planned(kind, key);
+ const { sent, result } = await wireOf(p);
+ assert.equal(B.acceptResultFor(p)(result), true, `${kind}: the SDK's own push result is accepted`);
+ assert.equal(B.acceptResultFor(p)({ ...result, id: OTHER }), false);
+ assert.equal(B.acceptResultFor(p)({ ...result, saved: false }), false);
+ const classify = B.createClassifier([{ token: 't', planned: p }]);
+ const named = sent.map((req) => classify(req));
+ assert.ok(named.every(Boolean), `${kind}: every request is a planned row or effect`);
+ const rows = named.filter((c) => c.type === 'rows').flatMap((c) => c.rows.map((r) => r.kind)).sort();
+ assert.deepEqual(rows, p.plan.rows.map((r) => r.kind).sort(), `${kind}: each planned row is sent exactly once`);
+ const effects = named.filter((c) => c.type === 'effect').map((c) => `${c.kind}:${c.id}`).sort();
+ assert.deepEqual(effects, p.plan.effects.map((e) => `${e.kind}:${e.id}`).sort(), `${kind}: and each planned effect`);
+ const text = JSON.stringify(named);
+ assert.ok(!text.includes(VALUE) && !text.includes(CONNECTION), `${kind}: no private input in a descriptor`);
+ }
+});
+
+test('the classifier refuses anything but the plan: ids, parents, columns, values, queries, solutions, shapes', async () => {
+ const api = planned('customApi', 'contoso_Calc');
+ const ev = planned('environmentVariable', 'contoso_ApiBase');
+ const cr = planned('connectionReference', 'contoso_sp');
+ const rule = planned('duplicateRule', 'email');
+ const unpublished = planned('duplicateRule', 'email', { spec: spec({ duplicateDetectionRules: [{ key: 'email', name: 'Same email', entity: 'contact', status: 'unpublished', conditions: [{ key: 'e', column: 'emailaddress1', match: 'exact' }] }] }) });
+ const wire = {};
+ for (const p of [api, ev, cr, rule]) wire[p.kind] = (await wireOf(p)).sent;
+ const classify = B.createClassifier([{ token: 'a', planned: api }, { token: 'e', planned: ev }, { token: 'c', planned: cr }, { token: 'r', planned: rule }]);
+ const [apiPost, apiMember] = wire.customApi;
+ const [defPost, valuePost] = wire.environmentVariable;
+ const [crPost] = wire.connectionReference;
+ const [rulePost, publish] = wire.duplicateRule;
+ assert.ok(classify(apiPost) && classify(defPost) && classify(valuePost) && classify(crPost) && classify(rulePost) && classify(publish) && classify(apiMember));
+ const reqId = rowOf(api, 'customApiRequestParameter').id;
+ const respId = rowOf(api, 'customApiResponseProperty').id;
+ const refused = [
+ ['child ids swapped', withBody(apiPost, (b) => { b.CustomAPIRequestParameters[0].customapirequestparameterid = respId; b.CustomAPIResponseProperties[0].customapiresponsepropertyid = reqId; })],
+ ['a child moved to the other direction', withBody(apiPost, (b) => { b.CustomAPIResponseProperties.push(b.CustomAPIRequestParameters.pop()); })],
+ ['a planned child left out of the deep insert', withBody(apiPost, (b) => { b.CustomAPIResponseProperties = []; })],
+ ['a nested child binding a parent', withBody(apiPost, (b) => { b.CustomAPIRequestParameters[0]['[email protected]'] = `/customapis(${OTHER})`; })],
+ ['an unknown column', withBody(apiPost, (b) => { b.iscustomizable = true; })],
+ ['an option code outside the table', withBody(apiPost, (b) => { b.bindingtype = 7; })],
+ ['another value', withBody(apiPost, (b) => { b.isfunction = false; })],
+ ['an unplanned id', withBody(apiPost, (b) => { b.customapiid = OTHER; })],
+ ['a query beyond the id', { ...apiPost, url: `${apiPost.url}&$top=1` }],
+ ['another solution', { ...defPost, headers: { ...defPost.headers, 'MSCRM.SolutionUniqueName': 'Fabrikam' } }],
+ ['a value row with a solution header', { ...valuePost, headers: { ...valuePost.headers, 'MSCRM.SolutionUniqueName': SOL } }],
+ ['a value under another definition', withBody(valuePost, (b) => { b['[email protected]'] = `/environmentvariabledefinitions(${OTHER})`; })],
+ ['a value under no definition', withBody(valuePost, (b) => { delete b['[email protected]']; })],
+ ['a column this build never writes', withBody(crPost, (b) => { b.promptingbehavior = 1; })],
+ ['a column this build never writes, sent as the platform default', withBody(crPost, (b) => { b.promptingbehavior = 0; })],
+ ['a column this build never writes, sent as an explicit null', withBody(crPost, (b) => { b.promptingbehavior = null; })],
+ ['a column this build never writes, sent as the default in another type', withBody(crPost, (b) => { b.promptingbehavior = '0'; })],
+ ['a definition kept by Dataverse', withBody(defPost, (b) => { b.secretstore = 1; })],
+ ['a rule without its condition', withBody(rulePost, (b) => { b.DuplicateRule_DuplicateRuleConditions = []; })],
+ ['a condition on its own', { method: 'POST', url: `${rulePost.url.replace('duplicaterules', 'duplicateruleconditions')}`, headers: {}, body: JSON.stringify(JSON.parse(rulePost.body).DuplicateRule_DuplicateRuleConditions[0]) }],
+ ['a planned create PATCHed', { method: 'PATCH', url: apiPost.url.replace(/customapis\?.*$/, `customapis(${api.plan.rows[0].id})`), headers: {}, body: JSON.stringify({ description: 'x' }) }],
+ ['a membership adding required components', withBody(apiMember, (b) => { b.AddRequiredComponents = true; })],
+ ['a membership of another type', withBody(apiMember, (b) => { b.ComponentType = 4414; })],
+ ['a membership of another solution', withBody(apiMember, (b) => { b.SolutionUniqueName = 'Fabrikam'; })],
+ ['a publish with a body', { ...publish, body: JSON.stringify({ x: 1 }) }],
+ ['a removal', { method: 'DELETE', url: apiPost.url.replace(/customapis\?.*$/, `customapis(${api.plan.rows[0].id})`), headers: {} }],
+ ];
+ for (const [what, req] of refused) assert.equal(classify(req), null, what);
+ assert.equal(B.createClassifier([{ token: 'u', planned: unpublished }])(publish), null, 'a publish the plan does not declare');
+
+ const valueSwap = thrown(() => classify(withBody(valuePost, (b) => { b.value = 'someone-else'; })));
+ assert.equal(valueSwap && valueSwap.code, B.PRIVATE_MISMATCH);
+ assert.ok(!valueSwap.message.includes('someone-else') && !valueSwap.message.includes(VALUE), 'the refusal names no private input');
+ const connSwap = thrown(() => classify(withBody(crPost, (b) => { b.connectionid = 'another-connection'; })));
+ assert.equal(connSwap && connSwap.code, B.PRIVATE_MISMATCH);
+ assert.throws(() => B.createClassifier([{ token: 'a', planned: api }, { token: 'b', planned: planned('customApi', 'contoso_Calc') }]), /planned twice/);
+});
+
+test('a bound Custom API edit as the real SDK sends it: the root PATCH on its own or in a change set, a child\'s labels on their own', async () => {
+ const fresh = planned('customApi', 'contoso_Calc');
+ const w = await wireOf(fresh);
+ const [apiPost, member] = w.sent;
+ assert.equal(B.classifyConstituent([{ token: 't', planned: fresh }], apiPost), null, 'a root create');
+ assert.equal(B.classifyConstituent([{ token: 't', planned: fresh }], member), null, 'a membership');
+ const root = fresh.plan.rows[0].id;
+ const api = (over) => spec({ customApis: [{ ...spec().customApis[0], ...over }] });
+
+ // The root alone: one direct PATCH, the selected primary key in its query and the held row version in If-Match.
+ const priv = await rebound(w.sdk.dataverse, fresh, { spec: api({ isPrivate: true }) });
+ assert.deepEqual(priv.plan.rows.map((r) => r.id), fresh.plan.rows.map((r) => r.id), 'a bound plan keeps the ids it was created at');
+ assert.equal(priv.plan.baseObservation.rowVersion, priv.rows[0].ifMatch);
+ const one = await pushEdit(w, 'customApi', root, [['/isPrivate', true]]);
+ assert.equal(one.result.saved, true);
+ const [patch] = one.sent;
+ assert.match(patch.url, /customapis\([^)]+\)\?\$select=customapiid$/);
+ const entries = [{ token: 't', planned: priv }];
+ assert.deepEqual(B.createClassifier(entries)(patch).rows.map((r) => r.kind), ['customApi'], 'the direct PATCH');
+ assert.deepEqual(B.classifyConstituent(entries, patch).rows.map((r) => r.kind), ['customApi'], 'the same PATCH in a change set');
+ assert.equal(B.createClassifier(entries)({ ...patch, url: patch.url.replace(/\?.*$/, '') }), null, 'without the selected key');
+ assert.equal(B.createClassifier(entries)({ ...patch, url: `${patch.url},name` }), null, 'selecting more');
+ assert.equal(B.createClassifier(entries)(withBody(patch, (b) => { b.isprivate = false; })), null, 'a PATCH to another value');
+
+ // A child's labels alone, in both directions: a direct PATCH of that child.
+ for (const [pointer, value, over, kind] of [
+ ['/requestParameters/0/description', 'Arg', { requestParameters: [{ uniqueName: 'A', type: 'integer', description: 'Arg' }] }, 'customApiRequestParameter'],
+ ['/responseProperties/0/name', 'contoso_Calc.R2', { responseProperties: [{ uniqueName: 'R', type: 'string', name: 'contoso_Calc.R2' }] }, 'customApiResponseProperty'],
+ ]) {
+ const p = await rebound(w.sdk.dataverse, fresh, { spec: api({ isPrivate: true, ...over }) });
+ const edit = await pushEdit(w, 'customApi', root, [[pointer, value]]);
+ assert.equal(edit.result.saved, true);
+ assert.equal(edit.sent.length, 1);
+ const named = B.createClassifier([{ token: 't', planned: p }])(edit.sent[0]);
+ assert.deepEqual(named && named.rows.map((r) => [r.kind, r.parentId]), [[kind, root]], `${kind}: the SDK's own label PATCH`);
+ assert.equal(B.classifyConstituent([{ token: 't', planned: p }], edit.sent[0]), null, `${kind}: never a constituent`);
+ assert.equal(B.createClassifier([{ token: 't', planned: p }])(withBody(edit.sent[0], (b) => { b.type = 10; })), null, `${kind}: more than its labels`);
+ }
+
+ // The root with a later child, in both directions: one $batch whose constituents are the root PATCH and the child POST.
+ for (const [list, add, kind, isPrivate] of [
+ ['requestParameters', { uniqueName: 'B', type: 'string', isOptional: true }, 'customApiRequestParameter', false],
+ ['responseProperties', { uniqueName: 'S', type: 'string' }, 'customApiResponseProperty', true],
+ ]) {
+ const declared = spec().customApis[0];
+ const p = await rebound(w.sdk.dataverse, fresh, {
+ spec: api({ isPrivate, requestParameters: declared.requestParameters, responseProperties: declared.responseProperties, [list]: [...declared[list], add] }),
+ });
+ const added = p.rows.find((r) => r.kind === kind && r.mode === 'create');
+ const edit = await pushEdit(w, 'customApi', root, [['/isPrivate', isPrivate], [`/${list}`, B.artifactFor(p)[list]]]);
+ assert.equal(edit.result.saved, true);
+ assert.deepEqual(edit.sent.map((r) => r.url.replace(/^.*\/api\/data\/v9\.\d\//, '')), ['$batch']);
+ assert.equal(B.createClassifier([{ token: 't', planned: p }])(edit.sent[0]), null, 'the $batch itself is refused today');
+ const parts = constituentsOf(edit.sent[0]);
+ assert.deepEqual(parts.map((c) => c.method), ['PATCH', 'POST']);
+ const named = parts.map((c) => B.classifyConstituent([{ token: 't', planned: p }], c));
+ assert.deepEqual(named.map((n) => n && n.rows.map((r) => r.id)), [[root], [added.id]], `${kind}: each constituent is its planned row`);
+ assert.equal(B.classifyConstituent([{ token: 't', planned: p }], { ...parts[1], url: parts[1].url.replace(/\?.*$/, '') }), null, 'a child POST without its selected key');
+ assert.equal(B.classifyConstituent([{ token: 't', planned: fresh }], parts[1]), null, 'a child POST under a root the plan creates');
+ const created = planned('customApi', 'contoso_Calc', { spec: api({ isPrivate, requestParameters: declared.requestParameters, responseProperties: declared.responseProperties, [list]: [...declared[list], add] }) });
+ assert.equal(rowOf(created, kind) && created.rows.find((r) => r.id === added.id).mode, 'create');
+ assert.equal(B.classifyConstituent([{ token: 't', planned: created }], parts[1]), null, 'the same child POST when the plan creates its root');
+ }
+
+ // The root with a child's labels: the change set's child PATCH is refused; it is admitted only on its own.
+ const both = await rebound(w.sdk.dataverse, fresh, { spec: api({ isPrivate: false, requestParameters: [{ uniqueName: 'A', type: 'integer', displayName: 'X' }] }) });
+ const mixed = await pushEdit(w, 'customApi', root, [['/isPrivate', false], ['/requestParameters/0/displayName', 'X']]);
+ const parts = constituentsOf(mixed.sent[0]);
+ assert.deepEqual(parts.map((c) => [c.method, c.url.replace(/^.*\/api\/data\/v9\.\d\/|\(.*$/g, '')]), [['PATCH', 'customapis'], ['PATCH', 'customapirequestparameters']]);
+ assert.ok(B.classifyConstituent([{ token: 't', planned: both }], parts[0]));
+ assert.equal(B.classifyConstituent([{ token: 't', planned: both }], parts[1]), null, 'a child label PATCH in a change set');
+ assert.ok(B.createClassifier([{ token: 't', planned: both }])(parts[1]), 'the same PATCH sent on its own');
+});
+
+test('a bound Custom API\'s registered implementation is kept exactly: never written, and the edit is proved only while the row holds that one', async () => {
+ const PLUGIN = '00000000-0000-4000-8000-0000000000aa';
+ const fresh = planned('customApi', 'contoso_Calc');
+ assert.deepEqual(fresh.rows.map((r) => r.preserved), [{}, {}, {}], 'a create expects no implementation');
+ const w = await wireOf(fresh);
+ const row = w.org.rows('customapis')[0];
+ row._plugintypeid_value = PLUGIN;
+ const dv = w.sdk.dataverse;
+ // A create is still proved only with no implementation: one on the row is not the row it made.
+ assert.notEqual((await B.observe(dv, fresh)).rows[0].projectionSha256, fresh.rows[0].expectedSha256);
+
+ const root = fresh.plan.rows[0].id;
+ const p = await rebound(dv, fresh, { spec: spec({ customApis: [{ ...spec().customApis[0], isPrivate: true }] }) });
+ assert.deepEqual(p.rows[0].preserved, { _plugintypeid_value: PLUGIN }, 'the exact plug-in type of the base read');
+ assert.deepEqual(p.rows.slice(1).map((r) => r.preserved), [{}, {}]);
+ assert.equal((await B.editShapeOf(dv, p)).rootChanged, true, 'the edit itself is the only difference');
+ const edit = await pushEdit(w, 'customApi', root, [['/isPrivate', true]]);
+ assert.equal(edit.sent.length, 1);
+ const [patch] = edit.sent;
+ assert.ok(!/plugintype/i.test(patch.body), 'the SDK sends no implementation');
+ const classify = B.createClassifier([{ token: 't', planned: p }]);
+ assert.ok(classify(patch), 'the edit\'s own PATCH');
+ for (const [what, add] of [['the implementation', { _plugintypeid_value: PLUGIN }], ['a clear of it', { _plugintypeid_value: null }], ['a bind to it', { '[email protected]': `/plugintypes(${PLUGIN})` }]]) {
+ assert.equal(classify(withBody(patch, (b) => Object.assign(b, add))), null, `a PATCH carrying ${what}`);
+ }
+ assert.equal(row._plugintypeid_value, PLUGIN);
+ const after = await B.observe(dv, p);
+ assert.equal(after.rows[0].projectionSha256, p.rows[0].expectedSha256, 'proved with the implementation it was planned over');
+ for (const changed of ['00000000-0000-4000-8000-0000000000bb', null]) {
+ row._plugintypeid_value = changed;
+ assert.notEqual((await B.observe(dv, p)).rows[0].projectionSha256, p.rows[0].expectedSha256, `an implementation ${changed ? 'replaced' : 'removed'}`);
+ }
+});
+
+test('a PATCH carries exactly the row version the plan was prepared from; an update without a fresh base read is not planned', () => {
+ const s = spec({ customApis: [{ ...spec().customApis[0], isPrivate: true }] });
+ const base = (over = {}) => ({ state: 'present', kind: 'customApi', id: OTHER, parentId: null, rowVersion: 'W/"3"', decoded: { fields: { name: 'n', displayName: 'd', description: 'x' } }, ...over });
+ const bound = (b) => planned('customApi', 'contoso_Calc', { spec: s, boundIdOf: (k) => (k === 'customApi' ? OTHER : undefined), bases: b === undefined ? undefined : new Map([[OTHER, b]]) });
+ const p = bound(base());
+ assert.equal(p.rows[0].ifMatch, 'W/"3"');
+ assert.deepEqual(p.plan.baseObservation && p.plan.baseObservation.rowVersion, 'W/"3"');
+ assert.equal(bound(base({ rowVersion: 'W/"4"' })).plan.declarationSha256, p.plan.declarationSha256, 'a version is no part of the declaration');
+ assert.deepEqual([p.rows[0].expected.name, p.rows[0].expected.displayName, p.rows[0].expected.description], ['n', 'd', 'x'], 'labels the App Spec leaves out are the row\'s own');
+ for (const [what, b] of [['no base', undefined], ['an absent base', { state: 'absent' }], ['another row\'s', base({ id: '11111111-1111-4111-8111-111111111111' })],
+ ['another kind\'s', base({ kind: 'connectionReference' })], ['no version', base({ rowVersion: null })], ['a wildcard version', base({ rowVersion: '*' })]]) {
+ assert.throws(() => bound(b), /no fresh base read with a row version/, what);
+ }
+ const classify = B.createClassifier([{ token: 't', planned: p }]);
+ const url = `https://contoso.crm.dynamics.com/api/data/v9.0/customapis(${OTHER})?$select=customapiid`;
+ const req = (headers) => ({ method: 'PATCH', url, headers, body: JSON.stringify({ isprivate: true }) });
+ assert.ok(classify(req({ 'If-Match': 'W/"3"' })), 'the held version');
+ assert.ok(classify(req({ 'if-match': 'W/"3"' })), 'in any spelling');
+ for (const [what, headers] of [['no condition', {}], ['the wildcard', { 'If-Match': '*' }], ['another version', { 'If-Match': 'W/"999"' }],
+ ['an older version', { 'If-Match': 'W/"2"' }], ['a list of versions', { 'If-Match': 'W/"3", W/"4"' }], ['two spellings', { 'If-Match': 'W/"3"', 'if-match': 'W/"3"' }],
+ ['a version that is not text', { 'If-Match': ['W/"3"'] }]]) {
+ assert.equal(classify(req(headers)), null, what);
+ }
+});
+
+test('Custom API labels: the plan pins what the SDK fills in, and the bundled SDK sends the same body from an unpinned artifact', async () => {
+ const authored = spec({ customApis: [{ uniqueName: 'contoso_Calc', displayName: 'Calc', requestParameters: [{ uniqueName: 'A', type: 'integer', displayName: 'Alpha' }], responseProperties: [{ uniqueName: 'R', type: 'string', description: 'Result' }] }] });
+ for (const s of [spec(), authored]) {
+ const p = planned('customApi', 'contoso_Calc', { spec: s });
+ const unpinned = B.artifactFor(p);
+ const declared = s.customApis[0];
+ const strip = (o, from) => { for (const f of ['name', 'displayName', 'description']) if (from[f] === undefined) delete o[f]; };
+ strip(unpinned, declared);
+ unpinned.requestParameters.forEach((c, i) => strip(c, declared.requestParameters[i]));
+ unpinned.responseProperties.forEach((c, i) => strip(c, declared.responseProperties[i]));
+ const pinnedPost = (await wireOf(p)).sent[0];
+ const rawPost = (await wireOf(p, { artifact: unpinned })).sent[0];
+ assert.deepEqual(JSON.parse(rawPost.body), JSON.parse(pinnedPost.body), 'the SDK fills an unset label exactly as the plan pins it');
+ assert.ok(B.createClassifier([{ token: 't', planned: p }])(rawPost));
+ }
+ const p = planned('customApi', 'contoso_Calc', { spec: authored });
+ const [root, req, resp] = [p.rows[0].expected, rowOf(p, 'customApiRequestParameter').expected, rowOf(p, 'customApiResponseProperty').expected];
+ assert.deepEqual([root.name, root.displayName, root.description], ['contoso_Calc', 'Calc', 'Calc']);
+ assert.deepEqual([req.name, req.displayName, req.description], ['contoso_Calc.A', 'Alpha', 'Alpha']);
+ assert.deepEqual([resp.name, resp.displayName, resp.description], ['contoso_Calc.R', 'R', 'Result']);
+ const classify = B.createClassifier([{ token: 't', planned: p }]);
+ const post = (await wireOf(p)).sent[0];
+ assert.equal(classify(withBody(post, (b) => { b.name = 'Unplanned root label'; })), null, 'a root label the plan does not hold');
+ assert.equal(classify(withBody(post, (b) => { b.CustomAPIRequestParameters[0].description = 'Unplanned'; })), null, 'a child label the plan does not hold');
+});
+// The real lifecycle: the SDK behind the real send-once gate, bound to a real binding store.
+async function lifecycle() {
+ const org = orgOf();
+ const gate = createDeferredManagedCreateGate();
+ const sdk = await sdkOf(org, gate);
+ const storeDir = makeTempDir('cfg-create-store-');
+ const store = openManagedBindings({ workspaceDir: storeDir, environment: org.origin, appUniqueName: 'contoso_app', solutionUniqueName: SOL });
+ gate.bind(store);
+ const ctx = createManagedCreateContext({ store, notFoundCode: B.NOT_FOUND_CODE });
+ return { org, sdk, dv: sdk.dataverse, store, storeDir, ctx };
+}
+const filesUnder = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? filesUnder(path.join(dir, e.name)) : [path.join(dir, e.name)]));
+
+test('one create set end to end: the SDK\'s own push and memberships through the gate, observed, settled and committed', async () => {
+ const { org, sdk, dv, storeDir, ctx } = await lifecycle();
+ assert.deepEqual(await B.readComponentTypes(dv), { complete: true, types: TYPES });
+ const plans = ALL.map(([kind, key]) => planned(kind, key));
+ for (const p of plans) assert.equal((await B.readConfigurationConflicts(dv, p)).state, 'clear');
+ const attempts = ctx.begin(plans.map((p) => p.plan));
+ const classify = B.createClassifier(plans.map((p, i) => ({ token: attempts[i].token, planned: p })));
+ const scope = (i, acceptResult, fn) => ctx.run({ attempts: [attempts[i]], classify, deleteCode: B.DELETE_CODE, label: 'configuration create', acceptResult }, fn);
+ for (const [i, p] of plans.entries()) {
+ const pushed = await scope(i, B.acceptResultFor(p), async () => {
+ await sdk.createArtifact(p.kind, B.artifactFor(p));
+ return sdk.pushArtifact(p.kind, p.plan.rows[0].id);
+ });
+ assert.deepEqual([pushed.error, pushed.localError, pushed.checked], [null, null, true], `${p.kind}: a checked push`);
+ // The members the platform did not add with the solution header (a rule's condition), added by the driver.
+ const missing = (await B.observe(dv, p)).members.filter((m) => m.state === 'absent').map((m) => p.plan.members.find((x) => x.id === m.id));
+ const added = await scope(i, undefined, async () => {
+ for (const m of missing) await dv.post('/AddSolutionComponent', { ComponentId: m.id, ComponentType: m.componentType, SolutionUniqueName: SOL, AddRequiredComponents: false });
+ });
+ assert.equal(added.localError, null);
+ const [settled] = ctx.settle([{ token: attempts[i].token, observation: await B.observe(dv, p) }]);
+ assert.equal(settled.verdict.action, 'commit', `${p.kind}: ${settled.verdict.code || ''} ${settled.verdict.message || ''}`);
+ assert.deepEqual(settled.group.records.map((r) => [r.kind, r.id, r.origin]), p.plan.rows.map((r) => [r.kind, r.id, 'created']));
+ }
+ assert.equal(org.rows('duplicaterules')[0].statecode, 1, 'the rule was published inside its own create set');
+ assert.deepEqual(org.unexpected, []);
+ for (const file of filesUnder(storeDir)) {
+ const text = fs.readFileSync(file, 'utf8');
+ assert.ok(!text.includes(VALUE) && !text.includes(CONNECTION), `no private input in ${path.basename(file)}`);
+ }
+});
+
+test('a push carrying another private input is refused unsent, and the refusal names no value', async () => {
+ const { org, sdk, dv, ctx } = await lifecycle();
+ const p = planned('environmentVariable', 'contoso_ApiBase');
+ const [attempt] = ctx.begin([p.plan]);
+ const out = await ctx.run({ attempts: [attempt], classify: B.createClassifier([{ token: attempt.token, planned: p }]), deleteCode: B.DELETE_CODE, label: 'configuration create', acceptResult: B.acceptResultFor(p) }, async () => {
+ const artifact = B.artifactFor(p);
+ artifact.currentValue.value = 'someone-else';
+ await sdk.createArtifact(p.kind, artifact);
+ return sdk.pushArtifact(p.kind, p.plan.rows[0].id);
+ });
+ assert.equal(out.localError && out.localError.code, B.PRIVATE_MISMATCH);
+ assert.equal(out.checked, false);
+ assert.ok(!out.localError.message.includes('someone-else') && !out.localError.message.includes(VALUE));
+ assert.deepEqual(org.rows('environmentvariablevalues'), [], 'the value was never sent');
+ const [held] = ctx.settle([{ token: attempt.token, observation: await B.observe(dv, p) }]);
+ assert.equal(held.verdict.code, CODES.completion, 'the definition alone is not the planned set');
+});
+
+test('fake org paging is opt-in: without pageSize a collection is one page, as before', async () => {
+ const org = orgOf();
+ for (const n of [1, 2, 3]) await seed(org, 'connectionreferences', { connectionreferenceid: `00000000-0000-4000-8000-00000000000${n}`, connectionreferencelogicalname: `contoso_c${n}`, connectorid: SP });
+ const all = await org.request({ url: `${org.origin}/api/data/v9.2/connectionreferences?$select=connectionreferenceid`, method: 'GET', headers: {} });
+ const body = typeof all.body === 'string' ? JSON.parse(all.body) : all.body;
+ assert.equal(body.value.length, 3);
+ assert.equal(body['@odata.nextLink'], undefined);
+ const paged = orgOf({ pageSize: 2 });
+ for (const n of [1, 2, 3]) await seed(paged, 'connectionreferences', { connectionreferenceid: `00000000-0000-4000-8000-00000000000${n}`, connectionreferencelogicalname: `contoso_c${n}`, connectorid: SP });
+ const sdk = await sdkOf(paged, null);
+ const first = await sdk.dataverse.get('/connectionreferences?$select=connectionreferenceid');
+ assert.equal(first.body.value.length, 2);
+ const second = await sdk.dataverse.getAbsolute(first.body['@odata.nextLink']);
+ assert.deepEqual([second.body.value.length, second.body['@odata.nextLink']], [1, undefined]);
+});
+
+test('an environment variable\'s secret store is read and compared: empty or Key Vault is what a create makes, Dataverse differs, anything else is unknown', async () => {
+ const s = spec({ environmentVariables: [spec().environmentVariables[0], { schemaName: 'contoso_Secret', type: 'secret' }, { schemaName: 'contoso_Plain', type: 'string' }] });
+ for (const key of ['contoso_Secret', 'contoso_Plain']) {
+ const p = planned('environmentVariable', key, { spec: s });
+ const w = await wireOf(p);
+ const id = p.plan.rows[0].id;
+ const store = async (value) => {
+ const res = await w.org.request({ url: `${w.org.origin}/api/data/v9.2/environmentvariabledefinitions(${id})`, method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ secretstore: value }) });
+ assert.ok(res.statusCode < 300, `PATCH secretstore ${value}: ${res.statusCode}`);
+ };
+ const root = async (dv = w.sdk.dataverse) => {
+ const r = (await B.observe(dv, p)).rows[0];
+ return r.state === 'present' ? (r.projectionSha256 === p.rows[0].expectedSha256 ? 'same' : 'differs') : r.state;
+ };
+ assert.equal(await root(), 'same', `${key}: as created (the column left empty)`);
+ await store(0);
+ assert.equal(await root(), 'same', `${key}: Azure Key Vault, the column's default`);
+ await store(1);
+ assert.equal(await root(), 'differs', `${key}: a value kept by Dataverse is not the definition the plan made`);
+ await store(2);
+ assert.equal(await root(), 'unknown', `${key}: a store this build cannot read`);
+ await store(null);
+ const unselected = { ...w.sdk.dataverse, get: async (q) => {
+ const r = await w.sdk.dataverse.get(q);
+ if (!q.startsWith('/environmentvariabledefinitions(')) return r;
+ const body = { ...r.body };
+ delete body.secretstore;
+ return { ...r, body };
+ } };
+ assert.equal(await root(unselected), 'unknown', `${key}: a read without the column proves nothing about it`);
+ }
+});
+
+test('a rule is published once, by the create set that makes it: a bound rule\'s plan verifies its state and publishes nothing', async () => {
+ const created = planned('duplicateRule', 'email');
+ const id = created.plan.rows[0].id;
+ assert.deepEqual(created.plan.effects.filter((e) => e.kind === 'rule-state'), [{ kind: 'rule-state', id }]);
+ const publish = (ruleId) => ({ method: 'POST', url: `https://contoso.crm.dynamics.com/api/data/v9.0/duplicaterules(${ruleId})/Microsoft.Dynamics.CRM.PublishDuplicateRule`, headers: {}, body: '{}' });
+ assert.deepEqual(B.createClassifier([{ token: 't', planned: created }])(publish(id)), { type: 'effect', token: 't', kind: 'rule-state', id });
+ const unpublished = planned('duplicateRule', 'email', { spec: spec({ duplicateDetectionRules: [{ ...spec().duplicateDetectionRules[0], status: 'unpublished' }] }) });
+ assert.deepEqual(unpublished.plan.effects.filter((e) => e.kind === 'rule-state'), []);
+ const w = await wireOf(created);
+ const bound = await rebound(w.sdk.dataverse, created);
+ assert.deepEqual([bound.rows[0].mode, bound.plan.ruleState], ['update', 'published'], 'the state the rule must read back as');
+ assert.deepEqual(bound.plan.effects.filter((e) => e.kind === 'rule-state'), [], 'and no publish is planned for it');
+ assert.equal(B.createClassifier([{ token: 't', planned: bound }])(publish(id)), null, 'a publish of a bound rule');
+ // A bound rule whose App Spec omits its status keeps the row's state: a rule somebody unpublished is verified as
+ // unpublished, never published again. An authored status is the declared one.
+ const unpublish = await w.org.request({ url: `${w.org.origin}/api/data/v9.2/duplicaterules(${id})`, method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ statecode: 0, statuscode: 0 }) });
+ assert.ok(unpublish.statusCode < 300);
+ assert.equal((await rebound(w.sdk.dataverse, created)).plan.ruleState, 'unpublished');
+ const declared = spec({ duplicateDetectionRules: [{ ...spec().duplicateDetectionRules[0], status: 'published' }] });
+ assert.equal((await rebound(w.sdk.dataverse, created, { spec: declared })).plan.ruleState, 'published');
+});
+
+test('completion reads the root\'s whole child graph: a child the plan does not hold, on any page, is a difference; a graph not read whole is unknown', async () => {
+ // A condition added under the rule while it is still unpublished, then published inside the set: never the prepared rule.
+ {
+ const { org, sdk, dv, ctx } = await lifecycle();
+ const p = planned('duplicateRule', 'email');
+ const [attempt] = ctx.begin([p.plan]);
+ const classify = B.createClassifier([{ token: attempt.token, planned: p }]);
+ const run = (fn, acceptResult) => ctx.run({ attempts: [attempt], classify, deleteCode: B.DELETE_CODE, label: 'configuration create', acceptResult }, fn);
+ const artifact = B.artifactFor(p);
+ artifact.status = 'unpublished';
+ const pushed = await run(async () => { await sdk.createArtifact(p.kind, artifact); return sdk.pushArtifact(p.kind, p.plan.rows[0].id); }, B.acceptResultFor(p));
+ assert.equal(pushed.checked, true);
+ await seed(org, 'duplicateruleconditions', { duplicateruleconditionid: OTHER, baseattributename: 'lastname', matchingattributename: 'lastname', operatorcode: 0, ignoreblankvalues: false, '[email protected]': `/duplicaterules(${p.rows[0].id})` });
+ const done = await run(async () => {
+ for (const m of (await B.observe(dv, p)).members.filter((x) => x.state === 'absent')) {
+ const full = p.plan.members.find((x) => x.id === m.id);
+ await dv.post('/AddSolutionComponent', { ComponentId: m.id, ComponentType: full.componentType, SolutionUniqueName: SOL, AddRequiredComponents: false });
+ }
+ await dv.post(`/duplicaterules(${p.rows[0].id})/Microsoft.Dynamics.CRM.PublishDuplicateRule`, {});
+ });
+ assert.equal(done.localError, null);
+ const observation = await B.observe(dv, p);
+ assert.equal(observation.ruleState, 'published');
+ assert.deepEqual(observation.rows.slice(1).map((r) => r.projectionSha256 === rowOf(p, r.kind).expectedSha256), [true], 'the planned condition alone still reads as planned');
+ const [settled] = ctx.settle([{ token: attempt.token, observation }]);
+ assert.notEqual(settled.verdict.action, 'commit', 'a rule with a condition the plan never made is not the rule it prepared');
+ }
+ const differs = async (dv, p) => {
+ const r = (await B.observe(dv, p)).rows[0];
+ return r.state === 'present' ? (r.projectionSha256 === p.rows[0].expectedSha256 ? 'same' : 'differs') : r.state;
+ };
+ // A second value under the definition.
+ const ev = planned('environmentVariable', 'contoso_ApiBase');
+ const evWire = await wireOf(ev);
+ assert.equal(await differs(evWire.sdk.dataverse, ev), 'same');
+ await seed(evWire.org, 'environmentvariablevalues', { environmentvariablevalueid: OTHER, value: 'another', '[email protected]': `/environmentvariabledefinitions(${ev.rows[0].id})` });
+ assert.equal(await differs(evWire.sdk.dataverse, ev), 'differs', 'a value the plan does not hold');
+ // A child the plan does not hold, in each direction, the second on a later page.
+ const api = planned('customApi', 'contoso_Calc');
+ const root = api.rows[0].id;
+ for (const [set, body, opts] of [
+ ['customapirequestparameters', { customapirequestparameterid: OTHER, uniquename: 'Z', name: 'Z', displayname: 'Z', type: 10 }, {}],
+ ['customapiresponseproperties', { customapiresponsepropertyid: OTHER, uniquename: 'Z', name: 'Z', displayname: 'Z', type: 10 }, { pageSize: 1 }],
+ ]) {
+ const w = await wireOf(api, { org: orgOf(opts) });
+ assert.equal(await differs(w.sdk.dataverse, api), 'same', `${set}: the planned graph`);
+ await seed(w.org, set, { ...body, '[email protected]': `/customapis(${root})` });
+ const since = w.org.requests.length;
+ assert.equal(await differs(w.sdk.dataverse, api), 'differs', `${set}: an extra child`);
+ if (opts.pageSize) assert.ok(w.org.requests.slice(since).some((r) => r.path.startsWith('/customapiresponseproperties') && /\$skiptoken=/.test(r.path)), 'found on the second page');
+ }
+ // Any doubt about the graph leaves the root unknown.
+ const w = await wireOf(api);
+ const dv = w.sdk.dataverse;
+ const reqId = rowOf(api, 'customApiRequestParameter').id;
+ const around = (match, fn) => ({ ...dv, get: async (q) => (match.test(q) ? fn(q, await dv.get(q)) : dv.get(q)) });
+ const listOf = /^\/customapirequestparameters\?/;
+ for (const [what, reading] of [
+ ['a collection that cannot be read', around(listOf, () => ({ status: 500, body: {} }))],
+ ['a collection that does not end', around(listOf, (q, r) => ({ ...r, body: { ...r.body, '@Microsoft.Dynamics.CRM.morerecords': true } }))],
+ ['a row under another parent', around(listOf, (q, r) => ({ ...r, body: { value: r.body.value.map((x) => ({ ...x, _customapiid_value: OTHER })) } }))],
+ ['a row named twice', around(listOf, (q, r) => ({ ...r, body: { value: [...r.body.value, ...r.body.value] } }))],
+ ['a row without an id', around(listOf, (q, r) => ({ ...r, body: { value: [...r.body.value, { _customapiid_value: root }] } }))],
+ ['a planned child listed but read absent', around(new RegExp(`^/customapirequestparameters\\(${reqId}\\)`), () => ({ status: 404, body: { error: { code: '0x80040217' } } }))],
+ ['a planned child read but not listed', around(listOf, (q, r) => ({ ...r, body: { value: [] } }))],
+ ]) {
+ assert.equal(await differs(reading, api), 'unknown', what);
+ }
+ assert.equal(await differs(dv, api), 'same');
+});
+
+test('a label someone else changed, or one the plan never held, is never certified', async () => {
+ const { org, sdk, dv, ctx } = await lifecycle();
+ const p = planned('customApi', 'contoso_Calc');
+ const [attempt] = ctx.begin([p.plan]);
+ const classify = B.createClassifier([{ token: attempt.token, planned: p }]);
+ const artifact = B.artifactFor(p);
+ artifact.name = 'Unplanned root label';
+ artifact.requestParameters[0].name = 'Unplanned child label';
+ const run = await ctx.run({ attempts: [attempt], classify, deleteCode: B.DELETE_CODE, label: 'configuration create', acceptResult: B.acceptResultFor(p) }, async () => {
+ await sdk.createArtifact(p.kind, artifact);
+ return sdk.pushArtifact(p.kind, p.plan.rows[0].id);
+ });
+ assert.equal(run.checked, false);
+ assert.deepEqual(org.rows('customapis'), [], 'refused unsent');
+ const [settled] = ctx.settle([{ token: attempt.token, observation: await B.observe(dv, p) }]);
+ assert.notEqual(settled.verdict.action, 'commit');
+ // The planned labels, created as planned, then changed by someone else: the read-back differs on that row.
+ const w = await wireOf(p);
+ const reqId = rowOf(p, 'customApiRequestParameter').id;
+ const same = async () => (await B.observe(w.sdk.dataverse, p)).rows.map((r) => r.projectionSha256 === rowOf(p, r.kind).expectedSha256);
+ assert.deepEqual(await same(), [true, true, true]);
+ const res = await w.org.request({ url: `${w.org.origin}/api/data/v9.2/customapirequestparameters(${reqId})`, method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ description: 'Changed' }) });
+ assert.ok(res.statusCode < 300);
+ assert.deepEqual(await same(), [true, false, true]);
+});
+
+test('pins: a data-source definition, every root\'s namesake predicate, a condition\'s namesake, private inputs out of every durable record', async () => {
+ const s23 = (over) => spec({ minimumPluginVersion: '2.23.0', ...over });
+ // A data-source definition: the SDK's own create classifies and reads back as planned.
+ const site = planned('environmentVariable', 'contoso_Site', { spec: s23({ environmentVariables: [spec().environmentVariables[0], { schemaName: 'contoso_Site', type: 'dataSource', connectorId: SP, parameterKey: 'dataset' }] }) });
+ const siteWire = await wireOf(site);
+ assert.ok(B.createClassifier([{ token: 't', planned: site }])(siteWire.sent.find((r) => /environmentvariabledefinitions/.test(r.url))));
+ assert.equal((await B.observe(siteWire.sdk.dataverse, site)).rows[0].projectionSha256, site.rows[0].expectedSha256);
+ // A namesake differing only in case (a rule's name with quotes and an ampersand) at another id is a conflict.
+ for (const [kind, key, data, set, body] of [
+ ['environmentVariable', 'contoso_Name', { environmentVariables: [{ schemaName: 'contoso_Name', type: 'string' }] }, 'environmentvariabledefinitions', { environmentvariabledefinitionid: OTHER, schemaname: 'CONTOSO_name', type: 100000000 }],
+ ['connectionReference', 'contoso_Name', { connectionReferences: [{ logicalName: 'contoso_Name', connectorId: SP }] }, 'connectionreferences', { connectionreferenceid: OTHER, connectionreferencelogicalname: 'CONTOSO_name', connectorid: SP }],
+ ['customApi', 'contoso_Name', { customApis: [{ uniqueName: 'contoso_Name' }] }, 'customapis', { customapiid: OTHER, uniquename: 'CONTOSO_name' }],
+ ['duplicateRule', 'rk', { duplicateDetectionRules: [{ key: 'rk', name: "O'Brien & sons", entity: 'contact', conditions: [] }] }, 'duplicaterules', { duplicateruleid: OTHER, name: "O'BRIEN & SONS", baseentityname: 'account', matchingentityname: 'account' }],
+ ]) {
+ const p = planned(kind, key, { spec: { minimumPluginVersion: '2.23.0', solution: { uniqueName: SOL, publisherPrefix: 'contoso' }, ...data } });
+ const org = orgOf();
+ await seed(org, set, body);
+ assert.equal((await B.readConfigurationConflicts((await sdkOf(org, null)).dataverse, p)).state, 'conflict', kind);
+ }
+ // A condition's namesake under a bound rule: every authored optional field and the actual parent.
+ const ruleBase = await B.readConfigurationRow(reader([[`/duplicaterules(${OTHER})`, { status: 200, body: {
+ '@odata.etag': 'W/"5"', duplicateruleid: OTHER, name: 'Same email', description: null, baseentityname: 'contact', matchingentityname: 'contact',
+ iscasesensitive: false, excludeinactiverecords: false, statecode: 1, statuscode: 2,
+ } }]]), 'duplicateRule', OTHER);
+ const rule = planned('duplicateRule', 'rk|/x', { spec: s23({ duplicateDetectionRules: [{ key: 'rk|/x', name: 'Same email', entity: 'contact', conditions: [{ key: 'ck|/y', column: 'emailaddress1', matchingColumn: 'lastname', match: 'firstCharacters', characters: 3, ignoreBlankValues: true }] }] }), boundIdOf: (k) => (k === 'duplicateRule' ? OTHER : undefined), bases: new Map([[OTHER, ruleBase]]) });
+ assert.equal(rule.rows[1].key, JSON.stringify(['rk|/x', 'ck|/y']));
+ const row = { duplicateruleconditionid: '11111111-1111-4111-8111-111111111111', baseattributename: 'EMAILADDRESS1', matchingattributename: 'LASTNAME', operatorcode: 1, operatorparam: 3, ignoreblankvalues: true, _regardingobjectid_value: OTHER };
+ for (const [change, expected] of [[{}, 'conflict'], [{ matchingattributename: 'emailaddress1' }, 'clear'], [{ operatorparam: 2 }, 'clear'], [{ ignoreblankvalues: false }, 'clear'],
+ [{ operatorcode: 2 }, 'clear'], [{ _regardingobjectid_value: row.duplicateruleconditionid }, 'unknown'], [{ operatorparam: '3' }, 'unknown'], [{ duplicateruleconditionid: 'not-a-guid' }, 'unknown']]) {
+ const dv = { get: async (q) => {
+ assert.ok(q.startsWith(`/duplicateruleconditions?$filter=_regardingobjectid_value eq ${OTHER}&$select=`));
+ return { status: 200, body: { value: [{ ...row, ...change }] } };
+ } };
+ assert.equal((await B.readConfigurationConflicts(dv, rule)).state, expected, JSON.stringify(change));
+ }
+ // Another private input changes neither the plan nor a sealed projection.
+ const priv = s23({ environmentVariables: [{ schemaName: 'contoso_Private', type: 'string' }], connectionReferences: [{ logicalName: 'contoso_ref', connectorId: SP }] });
+ const deploy = (v) => A.readDeploymentBindings({ EnvironmentVariables: [{ SchemaName: 'contoso_Private', Value: `value-${v}` }], ConnectionReferences: [{ LogicalName: 'contoso_ref', ConnectionId: `connection-${v}` }] }, priv);
+ for (const [kind, key, column] of [['environmentVariable', 'contoso_Private', 'value'], ['connectionReference', 'contoso_ref', 'connectionid']]) {
+ const p = B.planOf(priv, { kind, key, bindings: deploy('one'), solution: SOL, componentTypes: TYPES });
+ const q = B.planOf(priv, { kind, key, bindings: deploy('two'), solution: SOL, componentTypes: TYPES });
+ assert.deepEqual(p, q);
+ const req = (await wireOf(p)).sent.find((r) => r.body && Object.hasOwn(JSON.parse(r.body), column));
+ const other = withBody(req, (b) => { b[column] = column === 'value' ? 'value-two' : 'connection-two'; });
+ assert.deepEqual(B.createClassifier([{ token: 't', planned: p }])(req), B.createClassifier([{ token: 't', planned: q }])(other));
+ }
+});
+test('a bound row keeps what its App Spec omits: the expectation is the row read under the authored fields, never a create default', async () => {
+ const sameAs = async (dv, p, label) => {
+ const seen = await B.observe(dv, p);
+ for (const r of p.rows) assert.equal(seen.rows.find((x) => x.id === r.id).projectionSha256, r.expectedSha256, `${label}: ${r.kind}`);
+ };
+ // A Custom API made private, then edited by a description-only App Spec that no longer says so.
+ {
+ const s = spec({ customApis: [{ ...spec().customApis[0], isPrivate: true }] });
+ const first = planned('customApi', 'contoso_Calc', { spec: s });
+ const w = await wireOf(first);
+ const next = structuredClone(s);
+ delete next.customApis[0].isPrivate;
+ next.customApis[0].description = 'A description-only edit';
+ const q = await rebound(w.sdk.dataverse, first, { spec: next });
+ assert.equal(q.rows[0].expected.isPrivate, true, 'an omitted flag keeps the row\'s own value');
+ const edit = await pushEdit(w, 'customApi', first.rows[0].id, [['/description', 'A description-only edit']]);
+ assert.equal(edit.result.saved, true);
+ assert.deepEqual(Object.keys(JSON.parse(edit.sent[0].body)), ['description'], 'the SDK sends only the edited field');
+ assert.ok(B.createClassifier([{ token: 't', planned: q }])(edit.sent[0]), 'and that PATCH is the planned one');
+ await sameAs(w.sdk.dataverse, q, 'omitted isPrivate');
+ // An explicit false is still a change, and a create of the same App Spec still takes the create default.
+ const flipped = structuredClone(next);
+ flipped.customApis[0].isPrivate = false;
+ const r = await rebound(w.sdk.dataverse, first, { spec: flipped });
+ assert.equal(r.rows[0].expected.isPrivate, false);
+ assert.notEqual((await B.observe(w.sdk.dataverse, r)).rows[0].projectionSha256, r.rows[0].expectedSha256, 'an explicit false the row does not show yet');
+ assert.equal(planned('customApi', 'contoso_Calc', { spec: next }).rows[0].expected.isPrivate, false, 'a created row: the create default');
+ }
+ // An environment variable's default value and required flag, omitted by a later description-only edit.
+ {
+ const s = spec({ environmentVariables: [{ schemaName: 'contoso_ApiBase', type: 'string', defaultValue: 'fallback', isRequired: true }] });
+ const first = planned('environmentVariable', 'contoso_ApiBase', { spec: s });
+ const w = await wireOf(first);
+ const next = spec({ environmentVariables: [{ schemaName: 'contoso_ApiBase', type: 'string', description: 'A description-only edit' }] });
+ const q = await rebound(w.sdk.dataverse, first, { spec: next });
+ assert.deepEqual([q.rows[0].expected.defaultValue, q.rows[0].expected.isRequired], ['fallback', true]);
+ const edit = await pushEdit(w, 'environmentVariable', first.rows[0].id, [['/description', 'A description-only edit']]);
+ assert.equal(edit.result.saved, true);
+ await sameAs(w.sdk.dataverse, q, 'omitted defaultValue and isRequired');
+ const cleared = spec({ environmentVariables: [{ schemaName: 'contoso_ApiBase', type: 'string', description: 'A description-only edit', defaultValue: null, isRequired: false }] });
+ const c = await rebound(w.sdk.dataverse, first, { spec: cleared });
+ assert.deepEqual([c.rows[0].expected.defaultValue, c.rows[0].expected.isRequired], [null, false], 'an explicit null and false stay changes');
+ const created = planned('environmentVariable', 'contoso_ApiBase', { spec: next });
+ assert.deepEqual([created.rows[0].expected.defaultValue, created.rows[0].expected.isRequired], [null, false], 'a created row: the create defaults');
+ }
+ // A connection reference's description and connection, and a rule's flags and its condition's optional fields.
+ {
+ const s = spec({ connectionReferences: [{ logicalName: 'contoso_sp', connectorId: SP, description: 'Kept' }] });
+ const first = planned('connectionReference', 'contoso_sp', { spec: s });
+ const w = await wireOf(first);
+ const next = spec({ connectionReferences: [{ logicalName: 'contoso_sp', connectorId: SP }] });
+ const q = await rebound(w.sdk.dataverse, first, { spec: next, bindings: A.readDeploymentBindings({}, next) });
+ assert.deepEqual([q.rows[0].expected.description, q.rows[0].expected.connected], ['Kept', true], 'no binding asked: the row keeps its connection');
+ await sameAs(w.sdk.dataverse, q, 'omitted description and connection');
+ }
+ {
+ const declared = { key: 'email', name: 'Same email', entity: 'contact', caseSensitive: true, conditions: [{ key: 'e', column: 'emailaddress1', match: 'firstCharacters', characters: 3, ignoreBlankValues: true }] };
+ const first = planned('duplicateRule', 'email', { spec: spec({ duplicateDetectionRules: [declared] }) });
+ const w = await wireOf(first);
+ const next = spec({ duplicateDetectionRules: [{ key: 'email', name: 'Same email', entity: 'contact', conditions: [{ key: 'e', column: 'emailaddress1', match: 'firstCharacters' }] }] });
+ const q = await rebound(w.sdk.dataverse, first, { spec: next });
+ assert.equal(q.rows[0].expected.caseSensitive, true);
+ assert.deepEqual(q.rows[1].expected, { column: 'emailaddress1', matchingColumn: 'emailaddress1', match: 'firstCharacters', characters: 3, ignoreBlankValues: true });
+ await sameAs(w.sdk.dataverse, q, 'omitted rule flag and condition fields');
+ const created = planned('duplicateRule', 'email', { spec: next });
+ assert.deepEqual([created.rows[0].expected.caseSensitive, created.rows[1].expected.ignoreBlankValues, created.rows[1].expected.characters], [false, false, null], 'a created rule: the create defaults');
+ }
+});
+
+// Create one planned artifact through its own create set and commit it, as the lifecycle test does.
+async function createCommitted(h, p) {
+ const [attempt] = h.ctx.begin([p.plan]);
+ const classify = B.createSetClassifier([{ token: attempt.token, planned: p }]);
+ const scope = (fn, acceptResult) => h.ctx.run({ attempts: [attempt], classify, deleteCode: B.DELETE_CODE, label: 'configuration create', acceptResult }, fn);
+ const pushed = await scope(async () => {
+ await h.sdk.createArtifact(p.kind, B.artifactFor(p));
+ return h.sdk.pushArtifact(p.kind, p.plan.rows[0].id);
+ }, B.acceptResultFor(p));
+ assert.deepEqual([pushed.error, pushed.localError, pushed.checked], [null, null, true]);
+ await addMissingMembers(h, p, scope);
+ const [settled] = h.ctx.settle([{ token: attempt.token, observation: await B.observe(h.dv, p) }]);
+ assert.equal(settled.verdict.action, 'commit', `${settled.verdict.code || ''} ${settled.verdict.message || ''}`);
+ return settled;
+}
+async function addMissingMembers(h, p, scope) {
+ const missing = (await B.observe(h.dv, p)).members.filter((m) => m.state === 'absent').map((m) => p.plan.members.find((x) => x.id === m.id));
+ if (!missing.length) return;
+ const added = await scope(async () => {
+ for (const m of missing) await h.dv.post('/AddSolutionComponent', { ComponentId: m.id, ComponentType: m.componentType, SolutionUniqueName: SOL, AddRequiredComponents: false });
+ });
+ assert.equal(added.localError, null);
+}
+
+test('a bound Custom API edit is one checked change set end to end: the root PATCH with new children of both kinds, or new children only', async () => {
+ const api = (over) => spec({ customApis: [{ ...spec().customApis[0], ...over }] });
+ const declared = spec().customApis[0];
+ for (const [label, over, ops, want] of [
+ ['root plus both kinds', { isPrivate: true, requestParameters: [...declared.requestParameters, { uniqueName: 'B', type: 'string', isOptional: true }], responseProperties: [...declared.responseProperties, { uniqueName: 'S', type: 'integer' }] },
+ (p) => [['/isPrivate', true], ['/requestParameters', B.artifactFor(p).requestParameters], ['/responseProperties', B.artifactFor(p).responseProperties]], ['PATCH', 'POST', 'POST']],
+ ['children only, both kinds', { requestParameters: [...declared.requestParameters, { uniqueName: 'B', type: 'string' }], responseProperties: [...declared.responseProperties, { uniqueName: 'S', type: 'integer' }] },
+ (p) => [['/requestParameters', B.artifactFor(p).requestParameters], ['/responseProperties', B.artifactFor(p).responseProperties]], ['POST', 'POST']],
+ ]) {
+ const h = await lifecycle();
+ const fresh = planned('customApi', 'contoso_Calc');
+ await createCommitted(h, fresh);
+ const p = await rebound(h.dv, fresh, { spec: api(over), baseGeneration: h.store.readGroup('customApi', fresh.key).committed.generation });
+ const [attempt] = h.ctx.begin([p.plan]);
+ const classify = B.createSetClassifier([{ token: attempt.token, planned: p }]);
+ const batch = { apiBase: `${h.org.origin}/api/data/v9.0`, solution: SOL };
+ const scope = (fn, acceptResult) => h.ctx.run({ attempts: [attempt], classify, deleteCode: B.DELETE_CODE, label: 'configuration edit', acceptResult, batch }, fn);
+ const root = fresh.plan.rows[0].id;
+ const mark = h.org.requests.length;
+ const pushed = await scope(async () => {
+ await h.sdk.fetchArtifact('customApi', root, { overwrite: true });
+ for (const [pointer, value] of ops(p)) await h.sdk.updateElement('customApi', root, pointer, value);
+ return h.sdk.pushArtifact('customApi', root);
+ }, B.acceptResultFor(p));
+ const requests = h.org.requests.slice(mark).filter((r) => r.method !== 'GET');
+ assert.deepEqual([pushed.error, pushed.localError, pushed.checked], [null, null, true], `${label}: a checked change set`);
+ assert.deepEqual(requests.map((r) => r.path), ['/$batch'], `${label}: one request left`);
+ assert.deepEqual(requests[0].operations.map((c) => c.method), want);
+ await addMissingMembers(h, p, scope);
+ const [settled] = h.ctx.settle([{ token: attempt.token, observation: await B.observe(h.dv, p) }]);
+ assert.equal(settled.verdict.action, 'commit', `${label}: ${settled.verdict.code || ''} ${settled.verdict.message || ''}`);
+ const added = p.rows.filter((r) => r.mode === 'create').map((r) => r.id).sort();
+ assert.equal(added.length, 2);
+ assert.deepEqual(settled.group.records.filter((r) => added.includes(r.id)).map((r) => r.origin), ['created', 'created'], `${label}: the new children are this run's creates`);
+ assert.deepEqual(h.org.unexpected, []);
+ }
+});
+
+test('a change-set constituent the plan did not prepare is refused before anything is sent', async () => {
+ const h = await lifecycle();
+ const fresh = planned('customApi', 'contoso_Calc');
+ await createCommitted(h, fresh);
+ const declared = spec().customApis[0];
+ const p = await rebound(h.dv, fresh, { spec: spec({ customApis: [{ ...declared, isPrivate: true, requestParameters: [...declared.requestParameters, { uniqueName: 'B', type: 'string' }] }] }), baseGeneration: h.store.readGroup('customApi', fresh.key).committed.generation });
+ const root = fresh.plan.rows[0].id;
+ const [attempt] = h.ctx.begin([p.plan]);
+ // The SDK is asked for another child than the plan's (another type): the parser's constituent check refuses the set.
+ const other = B.artifactFor(p).requestParameters.map((c) => (c.uniqueName === 'B' ? { ...c, type: 'integer' } : c));
+ const mark = h.org.requests.length;
+ const out = await h.ctx.run({
+ attempts: [attempt], classify: B.createSetClassifier([{ token: attempt.token, planned: p }]), deleteCode: B.DELETE_CODE, label: 'configuration edit',
+ acceptResult: B.acceptResultFor(p), batch: { apiBase: `${h.org.origin}/api/data/v9.0`, solution: SOL },
+ }, async () => {
+ await h.sdk.fetchArtifact('customApi', root, { overwrite: true });
+ await h.sdk.updateElement('customApi', root, '/isPrivate', true);
+ await h.sdk.updateElement('customApi', root, '/requestParameters', other);
+ return h.sdk.pushArtifact('customApi', root);
+ });
+ const requests = h.org.requests.slice(mark).filter((r) => r.method !== 'GET');
+ assert.notEqual(out.localError, null, 'refused locally');
+ assert.deepEqual(requests, [], 'nothing was sent');
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/configuration-protected.test.js b/plugins/model-apps/scripts/tests/configuration-protected.test.js
new file mode 100644
index 000000000..e7f5fbd33
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/configuration-protected.test.js
@@ -0,0 +1,1230 @@
+'use strict';
+// Protected configuration (`configurationIdentity: "stable-v1"`): the opt-in, the whole-plan read-only preflight that stops an
+// unsupported edit before the build changes anything, and the build-side hookup of the configuration create driver.
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { createConfigOrg } = require('./helpers/fake-config-org.js');
+const { validateAppSpec, CONFIGURATION_IDENTITY_MIN_VERSION } = require('../lib/app-spec.js');
+const { lintAppSpec } = require('../lib/spec-lint.js');
+const { createAzHttpClient } = require('../lib/sdk-http-client.js');
+const { createMakerSdk, createNodeWorkspaceStorage } = require('../lib/maker-sdk.js');
+const { configurationSendOnce } = require('../lib/configuration-transport.js');
+const { createDeferredManagedCreateGate } = require('../lib/managed-create-transport.js');
+const { createManagedCreateContext } = require('../lib/managed-create-context.js');
+const { openManagedBindings, managedManifestView } = require('../lib/managed-bindings.js');
+const { readerFor } = require('../verify-model-app.js');
+const { createConfigurationRuntime } = require('../lib/configuration-build.js');
+const { readDeploymentBindings } = require('../lib/configuration-artifacts.js');
+const { runSdkBuild } = require('../lib/sdk-build.js');
+const { STAGES } = require('../lib/stages.js');
+const { RETRY } = require('../lib/retry-policy.js');
+const B = require('../lib/configuration-create-bindings.js');
+const P = require('../lib/configuration-protected.js');
+
+const SOL = 'ContosoSol';
+function baseSpec(extra = {}) {
+ return {
+ solution: { uniqueName: SOL, displayName: 'Contoso', publisherPrefix: 'contoso' },
+ app: { name: 'Configured', uniqueName: 'contoso_configured' },
+ entities: [{ schemaName: 'contoso_item', displayName: 'Item', existing: true, primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' } }],
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Records', subAreas: [{ entity: 'contoso_item', title: 'Items' }] }] }] },
+ environmentVariables: [{ schemaName: 'contoso_ApiBase', type: 'string', defaultValue: 'https://example.invalid' }],
+ ...extra,
+ };
+}
+
+test('configurationIdentity takes exactly "stable-v1" and asks for a 2.23.0 floor', () => {
+ const errorsOf = (spec) => validateAppSpec(spec).errors.filter((e) => /configurationIdentity/.test(e));
+ assert.equal(CONFIGURATION_IDENTITY_MIN_VERSION, '2.23.0');
+ assert.deepEqual(errorsOf(baseSpec()), []);
+ assert.deepEqual(errorsOf(baseSpec({ configurationIdentity: 'stable-v1' })), []);
+ for (const bad of ['stable-v2', 'Stable-V1', true, null, '', 1]) {
+ const errors = errorsOf(baseSpec({ configurationIdentity: bad }));
+ assert.equal(errors.length, 1, JSON.stringify(bad));
+ assert.match(errors[0], /^create-identity-invalid: configurationIdentity must be "stable-v1" or absent/);
+ }
+ // No alias: another spelling is not the opt-in (and createIdentity alone does not turn it on).
+ assert.deepEqual(errorsOf(baseSpec({ createIdentity: 'stable-v1' })), []);
+ const floor = (spec) => lintAppSpec(spec).warnings.filter((w) => /when using configurationIdentity/.test(w));
+ assert.equal(floor(baseSpec({ configurationIdentity: 'stable-v1' })).length, 1, 'no floor: older plugins ignore the field');
+ assert.equal(floor(baseSpec({ configurationIdentity: 'stable-v1', minimumPluginVersion: '2.22.0' })).length, 1);
+ assert.deepEqual(floor(baseSpec({ configurationIdentity: 'stable-v1', minimumPluginVersion: '2.23.0' })), []);
+ assert.deepEqual(floor(baseSpec()), [], 'no opt-in, no warning');
+ assert.equal(lintAppSpec(baseSpec({ configurationIdentity: 'stable-v1' })).errors.length, 0, 'a warning, never an error');
+});
+
+// ---------------------------------------------------------------------------------------------
+// The protected path against the fake org: the real SDK behind the real send-once gate, bound to a real binding store,
+// and the build's configuration runtime given the hookup (createProtectedConfiguration) the build makes over them.
+
+const API = { uniqueName: 'contoso_Calc', isFunction: true, requestParameters: [{ uniqueName: 'A', type: 'integer' }], responseProperties: [{ uniqueName: 'R', type: 'string' }] };
+const RULE = { key: 'email', name: 'Same email', entity: 'contact', conditions: [{ key: 'e', column: 'emailaddress1', match: 'exact' }] };
+function configSpec(over = {}) {
+ return {
+ // The opt-in asks for a 2.23.0 floor; this older floor only adds a lint warning, which these tests do not judge.
+ minimumPluginVersion: '2.21.0', configurationIdentity: 'stable-v1',
+ solution: { uniqueName: SOL, displayName: 'Contoso', publisherPrefix: 'contoso' },
+ app: { name: 'Configured', uniqueName: 'contoso_configured' }, schemaVersion: 2, entities: [],
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Links', subAreas: [{ url: 'https://contoso.example/help', title: 'Help' }] }] }] },
+ environmentVariables: [{ schemaName: 'contoso_ApiBase', type: 'string', defaultValue: 'https://api.contoso.com' }],
+ customApis: [API],
+ duplicateDetectionRules: [RULE],
+ ...over,
+ };
+}
+const api = (over) => ({ customApis: [{ ...API, ...over }] });
+const rule = (over) => ({ duplicateDetectionRules: [{ ...RULE, ...over }] });
+
+async function harness({ hookup = true, intercept } = {}) {
+ const org = createConfigOrg({ tables: [{ logicalName: 'contact', attributes: ['emailaddress1', 'lastname'] }], solution: { uniqueName: SOL, version: '1.0.0.0', prefix: 'contoso' }, ...(intercept ? { intercept } : {}) });
+ const gate = createDeferredManagedCreateGate();
+ const httpClient = createAzHttpClient(org.origin, { getToken: () => 'test-token-0123456789abcdef', request: org.request, sleep: async () => {}, sendOnce: configurationSendOnce, workflowEffectGate: gate });
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(makeTempDir('cfg-protected-sdk-')), instanceUrl: org.origin, httpClient, solutionUniqueName: SOL });
+ await sdk.initWorkspace();
+ const store = openManagedBindings({ workspaceDir: makeTempDir('cfg-protected-store-'), environment: org.origin, appUniqueName: 'contoso_configured', solutionUniqueName: SOL });
+ gate.bind(store);
+ const ctx = createManagedCreateContext({ store, notFoundCode: B.NOT_FOUND_CODE });
+ const protectedConfiguration = hookup ? P.createProtectedConfiguration({ store, gate, ctx, apiBase: `${org.origin}/api/data/v9.0` }) : undefined;
+ return { org, sdk, store, gate, ctx, protectedConfiguration };
+}
+// A later process over the same binding store: a fresh managed create context (none of the earlier answers), with the
+// maker's exact approvals.
+function reopen(h, approvals = []) {
+ const ctx = createManagedCreateContext({ store: h.store, approvals, notFoundCode: B.NOT_FOUND_CODE });
+ return { ...h, ctx, protectedConfiguration: P.createProtectedConfiguration({ store: h.store, gate: h.gate, ctx, apiBase: `${h.org.origin}/api/data/v9.0` }) };
+}
+// One configuration pass as the build runs it: the preflight, then the data-model step. Answers what it sent.
+async function pass(h, spec, opts = {}) {
+ const mark = h.org.requests.length;
+ const runtime = createConfigurationRuntime({ spec, sdk: h.sdk, opts: { protectedConfiguration: h.protectedConfiguration, ...opts }, appUniqueName: 'contoso_configured' });
+ let halt = null;
+ let step = null;
+ try {
+ await runtime.preflight();
+ step = await runtime.apply('data-model');
+ runtime.throwIfIncomplete(step);
+ } catch (error) {
+ halt = error;
+ }
+ return { halt, step, sent: h.org.requests.slice(mark).filter((r) => r.method !== 'GET') };
+}
+async function created(h, spec = configSpec(), opts = {}) {
+ const first = await pass(h, spec, opts);
+ assert.equal(first.halt, null, first.halt && `${first.halt.code}: ${first.halt.message}`);
+ return first;
+}
+const committed = (h, kind, key) => h.store.readGroup(kind, key).committed;
+// The maker's one approval that replaces a protected item's local copy with the server's, as build-model-app.js reads
+// `--authorize overwrite:<kind>:<key>` into opts.authorizedOverwrite (the flag minus its verb).
+const overwriteCopy = (kind, key) => ({ authorizedOverwrite: new Set([`${kind}:${key}`]) });
+// A build that found the item's local copy differing from the server's: it stops before any write, the copy kept, and
+// names the exact approval that replaces it.
+function assertCopyStop(out, kind, key) {
+ assert.equal(out.halt && out.halt.code, 'workspace-copy-unsent-edits', out.halt && `${out.halt.code}: ${out.halt.message}`);
+ assert.equal(out.halt.phase, 'preflight');
+ assert.ok(out.halt.message.includes(`--authorize overwrite:${kind}:${key}`), out.halt.message);
+ assert.deepEqual(out.sent, [], 'nothing is written while the local copy differs');
+}
+
+test('protected configuration is created at its derived ids through the binding store, and an unchanged rerun sends nothing', async () => {
+ const h = await harness();
+ const first = await created(h);
+ assert.ok(first.sent.length > 0);
+ for (const [kind, key] of [['environmentVariable', 'contoso_apibase'], ['customApi', 'contoso_calc'], ['duplicateRule', 'email']]) {
+ const group = committed(h, kind, key);
+ assert.ok(group, `${kind} is bound`);
+ assert.ok(group.records.every((r) => r.origin === 'created'), `${kind}: every row is this build's create`);
+ }
+ assert.equal(h.org.rows('duplicaterules')[0].statecode, 1, 'the rule completed its initial publication');
+ assert.deepEqual(h.org.unexpected, []);
+ const again = await pass(h, configSpec());
+ assert.equal(again.halt, null, again.halt && again.halt.message);
+ assert.deepEqual(again.sent, [], 'an unchanged rerun writes nothing');
+});
+
+test('under the opt-in without the binding store the build stops before any request is sent', async () => {
+ const h = await harness({ hookup: false });
+ const out = await pass(h, configSpec());
+ assert.equal(out.halt && out.halt.code, 'create-identity-unverified');
+ assert.equal(out.halt.phase, 'preflight');
+ assert.equal(out.halt.retry, RETRY.NEVER);
+ assert.match(out.halt.message, /No service changes were sent by this build/);
+ assert.deepEqual(h.org.requests, [], 'not even a read');
+});
+
+test('every later edit of a protected duplicate rule stops in preflight with nothing sent', async () => {
+ for (const [label, over] of [
+ ['a field', rule({ name: 'Same email address' })],
+ ['a condition', rule({ conditions: [{ key: 'e', column: 'lastname', match: 'exact' }] })],
+ ['an added condition', rule({ conditions: [...RULE.conditions, { key: 'l', column: 'lastname', match: 'exact' }] })],
+ ['the state', rule({ status: 'unpublished' })],
+ ]) {
+ const h = await harness();
+ await created(h);
+ const out = await pass(h, configSpec(over));
+ assert.equal(out.halt && out.halt.code, 'configuration-edit-unsupported', `${label}: ${out.halt && out.halt.message}`);
+ assert.equal(out.halt.phase, 'preflight');
+ assert.ok(out.halt.message.includes(P.RULE_EDIT_MESSAGE), label);
+ assert.deepEqual(out.sent, [], `${label}: nothing sent`);
+ }
+});
+
+test('first conditions, a removed condition, or an added condition with a field change of a protected rule stop in preflight', async () => {
+ const TWO = [...RULE.conditions, { key: 'l', column: 'lastname', match: 'exact' }];
+ for (const [label, base, over] of [
+ ['an added condition and a field', rule({}), rule({ name: 'Same email address', conditions: TWO })],
+ // A rule created unpublished without conditions is still only verified: its first conditions are an edit too.
+ ['first conditions and a name', rule({ status: 'unpublished', conditions: [] }), rule({ status: 'unpublished', name: 'Same email address' })],
+ ['a removed condition', rule({ conditions: TWO }), rule({})],
+ ]) {
+ const h = await harness();
+ await created(h, configSpec(base));
+ const out = await pass(h, configSpec(over));
+ assert.equal(out.halt && out.halt.code, 'configuration-edit-unsupported', `${label}: ${out.halt && out.halt.message}`);
+ assert.equal(out.halt.phase, 'preflight');
+ assert.ok(out.halt.message.includes(P.RULE_EDIT_MESSAGE), label);
+ assert.deepEqual(out.sent, [], `${label}: nothing sent`);
+ }
+});
+
+test('a rule unpublished outside the plugin is only verified: the rerun stops rather than publishing it again', async () => {
+ const h = await harness();
+ await created(h);
+ const id = committed(h, 'duplicateRule', 'email').records.find((r) => r.kind === 'duplicateRule').id;
+ const res = await h.org.request({ url: `${h.org.origin}/api/data/v9.2/duplicaterules(${id})`, method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ statecode: 0, statuscode: 0 }) });
+ assert.ok(res.statusCode < 300);
+ const out = await pass(h, configSpec(rule({ status: 'published' })));
+ assert.equal(out.halt && out.halt.code, 'configuration-edit-unsupported');
+ assert.deepEqual(out.sent, [], 'no publication is sent for a bound rule');
+});
+
+test('unsupported protected Custom API edits stop in preflight with nothing sent', async () => {
+ const B2 = { uniqueName: 'B', type: 'string' };
+ for (const [label, over, code] of [
+ ['the root and a child\'s labels', api({ isPrivate: true, requestParameters: [{ ...API.requestParameters[0], description: 'First' }] }), 'configuration-edit-unsupported'],
+ ['a child\'s labels and a new child', api({ requestParameters: [{ ...API.requestParameters[0], description: 'First' }, B2] }), 'configuration-edit-unsupported'],
+ ['two children\'s labels', api({ requestParameters: [{ ...API.requestParameters[0], description: 'First' }], responseProperties: [{ ...API.responseProperties[0], description: 'Result' }] }), 'configuration-edit-unsupported'],
+ ['a child\'s fixed field', api({ requestParameters: [{ ...API.requestParameters[0], type: 'string' }] }), 'configuration-edit-unsupported'],
+ ['a removed child', api({ responseProperties: [] }), B.DELETE_CODE],
+ ['a removed child and a root edit', api({ isPrivate: true, responseProperties: [] }), 'configuration-edit-unsupported'],
+ ]) {
+ const h = await harness();
+ await created(h);
+ const out = await pass(h, configSpec(over));
+ assert.equal(out.halt && out.halt.code, code, `${label}: ${out.halt && out.halt.message}`);
+ assert.equal(out.halt.phase, 'preflight');
+ if (code === 'configuration-edit-unsupported') assert.ok(out.halt.message.includes(P.API_EDIT_MESSAGE), label);
+ assert.deepEqual(out.sent, [], `${label}: nothing sent`);
+ }
+});
+
+test('supported protected Custom API edits are made through the binding store: one request, or one checked change set', async () => {
+ for (const [label, over, want] of [
+ ['the root alone', api({ description: 'Adds two numbers' }), ['PATCH']],
+ ['one child\'s labels', api({ requestParameters: [{ ...API.requestParameters[0], description: 'First' }] }), ['PATCH']],
+ ['one new child', api({ requestParameters: [...API.requestParameters, { uniqueName: 'B', type: 'string' }] }), ['POST']],
+ ['the root and new children', api({ description: 'Adds two numbers', requestParameters: [...API.requestParameters, { uniqueName: 'B', type: 'string' }], responseProperties: [...API.responseProperties, { uniqueName: 'S', type: 'integer' }] }), ['$batch']],
+ ['new children only', api({ requestParameters: [...API.requestParameters, { uniqueName: 'B', type: 'string' }], responseProperties: [...API.responseProperties, { uniqueName: 'S', type: 'integer' }] }), ['$batch']],
+ ]) {
+ const h = await harness();
+ await created(h);
+ const before = committed(h, 'customApi', 'contoso_calc');
+ const out = await pass(h, configSpec(over));
+ assert.equal(out.halt, null, `${label}: ${out.halt && `${out.halt.code}: ${out.halt.message}`}`);
+ const writes = out.sent.filter((r) => r.path !== '/AddSolutionComponent');
+ assert.deepEqual(writes.map((r) => (r.path === '/$batch' ? '$batch' : r.method)), want, label);
+ for (const r of writes.filter((w) => w.method === 'PATCH')) assert.match(String(r.headers['if-match'] || r.headers['If-Match']), /^W\/"\d+"$/, `${label}: the PATCH carries the row version it was planned from`);
+ const after = committed(h, 'customApi', 'contoso_calc');
+ assert.notEqual(after.generation, before.generation, `${label}: the edit was settled into the store`);
+ assert.ok(before.records.every((r) => after.records.some((x) => x.id === r.id)), `${label}: every bound row keeps its id`);
+ assert.deepEqual(h.org.unexpected, []);
+ const again = await pass(h, configSpec(over));
+ assert.equal(again.halt, null);
+ assert.deepEqual(again.sent, [], `${label}: the rerun writes nothing`);
+ }
+});
+
+test('under the opt-in the binding store, not the managed-artifacts manifest, names the row an edit is sent to', async () => {
+ const h = await harness();
+ await created(h);
+ const boundId = committed(h, 'customApi', 'contoso_calc').records.find((r) => r.kind === 'customApi').id;
+ const res = await h.org.request({ url: `${h.org.origin}/api/data/v9.2/customapis`, method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ uniquename: 'contoso_Other', name: 'contoso_Other', displayname: 'Other', bindingtype: 0, isfunction: true }) });
+ assert.ok(res.statusCode < 300);
+ const otherId = /\(([0-9a-f-]{36})\)/i.exec(res.headers['odata-entityid'])[1];
+ // A manifest record that names another row (stale, or written by an older build) must not stand in for the binding,
+ // and a bound row is this build's own create, not an adoption: the adoption policy (here refusing all) is not asked.
+ const asked = [];
+ const managed = { lookup: async (kind) => (kind === 'customApi' ? { id: otherId, childIds: {} } : null), recordApplied: async () => {},
+ planAdoption: async (row) => { asked.push(row); return { allowed: false, code: 'ADOPTION_REFUSED' }; } };
+ const out = await pass(h, configSpec(api({ description: 'Adds two numbers' })), { managed });
+ assert.equal(out.halt, null, out.halt && `${out.halt.code}: ${out.halt.message}`);
+ const patches = out.sent.filter((r) => r.method === 'PATCH');
+ assert.equal(patches.length, 1);
+ assert.ok(patches[0].path.includes(boundId), `the edit went to the bound row: ${patches[0].path}`);
+ assert.ok(!out.sent.some((r) => String(r.path).includes(otherId)), 'the manifest row is never written');
+ assert.deepEqual(asked, []);
+});
+test('a rule whose initial publication failed keeps it owed: the rerun never sends it again, and commits once it is published under the same id', async () => {
+ let failPublish = true;
+ const h = await harness({ intercept: ({ method, path }) => (failPublish && method === 'POST' && /PublishDuplicateRule$/.test(path) ? { statusCode: 400, body: { error: { code: '0x80040216', message: 'publish failed' } } } : undefined) });
+ const first = await pass(h, configSpec());
+ assert.ok(first.halt, 'the create is not complete');
+ const pending = h.store.readGroup('duplicateRule', 'email');
+ assert.equal(pending.committed, null);
+ assert.ok(pending.pending, 'the attempt stays pending with its original expectation');
+ assert.equal(pending.pending.rowProtocol.completion.ruleState, 'published', 'an omitted status owes the initial publication');
+ const ruleId = pending.pending.root.id;
+ assert.equal(h.org.rows('duplicaterules').find((r) => r.duplicateruleid === ruleId).statecode, 0);
+ failPublish = false;
+ const publishes = () => h.org.requests.filter((r) => /PublishDuplicateRule$/.test(r.path)).length;
+ const sentPublishes = publishes();
+
+ // The rerun proves the rows and the owed state at the same ids, and does not publish again. The failed send left
+ // the workspace copy as it was; the build stops on it until the maker approves replacing it with the server's.
+ assertCopyStop(await pass(h, configSpec()), 'duplicateRule', 'email');
+ const again = await pass(h, configSpec(), overwriteCopy('duplicateRule', 'email'));
+ assert.equal(again.halt && again.halt.code, 'create-completion-required', again.halt && again.halt.message);
+ assert.equal(again.halt.phase, 'preflight');
+ assert.deepEqual(again.sent, [], 'nothing is sent: the publication is not replayed');
+ assert.equal(publishes(), sentPublishes);
+
+ // A changed declaration is not reinterpreted from the row as it is now.
+ const changed = await pass(h, configSpec(rule({ status: 'unpublished' })));
+ assert.equal(changed.halt && changed.halt.code, 'managed-pending-intent-changed', changed.halt && changed.halt.message);
+ assert.deepEqual(changed.sent, []);
+
+ // The maker completes it under the same id. A later process proves the rows the plugin itself created and
+ // receipted, and binds them without sending anything.
+ const res = await h.org.request({ url: `${h.org.origin}/api/data/v9.2/duplicaterules(${ruleId})/Microsoft.Dynamics.CRM.PublishDuplicateRule`, method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
+ assert.ok(res.statusCode < 300);
+ const approved = reopen(h);
+ const done = await pass(approved, configSpec());
+ assert.equal(done.halt, null, done.halt && `${done.halt.code}: ${done.halt.message}`);
+ assert.deepEqual(done.sent, [], 'binding the completed create sends nothing');
+ assert.equal(publishes(), sentPublishes + 1, 'the rule was published once by the plugin, and once by the maker');
+ const group = committed(h, 'duplicateRule', 'email');
+ assert.ok(group && group.records.some((r) => r.id === ruleId));
+ const rerun = await pass(approved, configSpec());
+ assert.equal(rerun.halt, null);
+ assert.deepEqual(rerun.sent, []);
+});
+test('a rule whose create answer was lost is never re-created or published by a rerun, and is bound only under its exact approvals', async () => {
+ let org = null;
+ let lose = true;
+ // The service applies the create, and its answer is lost on the way back.
+ const h = await harness({ intercept: async (req) => {
+ if (!lose || req.method !== 'POST' || req.path.split('?')[0] !== '/duplicaterules') return undefined;
+ lose = false;
+ await org.request({ url: `${org.origin}/api/data/v9.0${req.path}`, method: 'POST', headers: req.headers, body: JSON.stringify(req.body) });
+ return { statusCode: 400, body: { error: { code: '0x80040216', message: 'the answer was lost' } } };
+ } });
+ org = h.org;
+ const first = await pass(h, configSpec());
+ assert.ok(first.halt, 'the outcome is unknown');
+ const ruleId = h.store.readGroup('duplicateRule', 'email').pending.root.id;
+ const writes = () => h.org.requests.filter((r) => r.method !== 'GET').length;
+
+ assertCopyStop(await pass(reopen(h), configSpec()), 'duplicateRule', 'email');
+ const again = await pass(reopen(h), configSpec(), overwriteCopy('duplicateRule', 'email'));
+ assert.equal(again.halt && again.halt.code, 'create-completion-required', again.halt && again.halt.message);
+ assert.deepEqual(again.sent, []);
+ assert.equal(h.org.rows('duplicaterules').length, 1, 'the rule is not created again');
+
+ // The maker completes it under the same id: its initial publication and its solution membership.
+ const before = writes();
+ await h.org.request({ url: `${h.org.origin}/api/data/v9.2/duplicaterules(${ruleId})/Microsoft.Dynamics.CRM.PublishDuplicateRule`, method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
+ const inSolution = new Set(h.org.rows('solutioncomponents').map((c) => c.objectid));
+ for (const m of h.store.readGroup('duplicateRule', 'email').pending.rowProtocol.completion.members) {
+ if (inSolution.has(m.id)) continue;
+ await h.org.request({ url: `${h.org.origin}/api/data/v9.2/AddSolutionComponent`, method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ SolutionUniqueName: SOL, ComponentId: m.id, ComponentType: m.componentType, AddRequiredComponents: false }) });
+ }
+ const makerWrites = writes() - before;
+
+ // No answer proved those rows this plugin's own: a later process asks for each row's exact approval and sends nothing.
+ const asked = await pass(reopen(h), configSpec());
+ assert.equal(asked.halt && asked.halt.code, 'create-ownership-required', asked.halt && asked.halt.message);
+ assert.deepEqual(asked.sent, []);
+ const quoted = /given after checking those rows are yours: (.*)\.$/.exec(asked.halt.message);
+ assert.ok(quoted, asked.halt.message);
+ const tokens = JSON.parse(`[${quoted[1]}]`);
+ assert.ok(tokens.includes('adopt:duplicateRule:email'), tokens.join(' '));
+ assert.ok(tokens.some((t) => t.startsWith('adopt:duplicateRuleCondition:')), tokens.join(' '));
+
+ // A wholesale or partial approval binds nothing.
+ const partial = await pass(reopen(h, ['adopt:duplicateRule:email']), configSpec());
+ assert.equal(partial.halt && partial.halt.code, 'create-ownership-required');
+
+ const approved = reopen(h, tokens);
+ const done = await pass(approved, configSpec());
+ assert.equal(done.halt, null, done.halt && `${done.halt.code}: ${done.halt.message}`);
+ assert.deepEqual(done.sent, []);
+ assert.equal(writes() - before, makerWrites, 'the plugin wrote nothing after the lost answer: no create, no publication');
+ assert.ok(committed(h, 'duplicateRule', 'email').records.some((r) => r.id === ruleId));
+});
+test('a bound row deleted outside the plugin is never replaced by a namesake: the build stops before any write', async () => {
+ const h = await harness();
+ await created(h);
+ const id = committed(h, 'customApi', 'contoso_calc').records.find((r) => r.kind === 'customApi').id;
+ const res = await h.org.request({ url: `${h.org.origin}/api/data/v9.2/customapis(${id})`, method: 'DELETE', headers: {} });
+ assert.ok(res.statusCode < 300);
+ const out = await pass(h, configSpec());
+ assert.equal(out.halt && out.halt.code, B.NOT_FOUND_CODE, out.halt && out.halt.message);
+ assert.deepEqual(out.sent, []);
+ assert.equal(h.org.rows('customapis').length, 0, 'nothing was created in its place');
+});
+
+test('the build runs the protected preflight before its first write: an earlier writable item and a version change are not sent', async () => {
+ const h = await harness();
+ await created(h);
+ const spec = configSpec({
+ solution: { uniqueName: SOL, displayName: 'Contoso', publisherPrefix: 'contoso', version: '1.2.0.0' },
+ environmentVariables: [{ schemaName: 'contoso_ApiBase', type: 'string', defaultValue: 'https://api2.contoso.com' }],
+ ...rule({ name: 'Same email address' }),
+ });
+ assert.deepEqual(validateAppSpec(spec).errors, []);
+ const mark = h.org.requests.length;
+ let caught;
+ try {
+ await runSdkBuild(spec, { sdk: h.sdk, apply: true, phases: STAGES.data, workspaceDir: makeTempDir('cfg-protected-ws-'), protectedConfiguration: h.protectedConfiguration, emit: () => {} });
+ } catch (error) {
+ caught = error;
+ }
+ assert.equal(caught && caught.code, 'configuration-edit-unsupported', caught && caught.message);
+ assert.equal(caught.phase, 'preflight');
+ assert.equal(caught.retry, RETRY.NEVER);
+ assert.deepEqual(h.org.requests.slice(mark).filter((r) => r.method !== 'GET'), [], 'zero service mutations');
+ assert.equal(h.org.rows('solutions').find((s) => s.uniquename === SOL).version, '1.0.0.0');
+});
+
+// A rule left pending: its initial publication was refused, so its attempt is unfinished in the binding store.
+async function pendingRule() {
+ const h = await harness({ intercept: ({ method, path }) => (method === 'POST' && /PublishDuplicateRule$/.test(path)
+ ? { statusCode: 400, body: { error: { code: '0x80040216', message: 'publish failed' } } } : undefined) });
+ assert.ok((await pass(h, configSpec({ environmentVariables: [], customApis: [] }))).halt);
+ assert.ok(h.store.readGroup('duplicateRule', 'email').pending);
+ return h;
+}
+
+test('dropping the declaration of a pending protected item never lets a build go on: with or without the opt-in, nothing is sent', async () => {
+ const h = await pendingRule();
+ const unrelated = configSpec({ customApis: [], duplicateDetectionRules: [], environmentVariables: [{ schemaName: 'contoso_Unrelated', type: 'string' }] });
+ const { configurationIdentity, ...plain } = unrelated;
+ for (const spec of [unrelated, plain]) {
+ const out = await pass(reopen(h), spec);
+ assert.equal(out.halt && out.halt.code, 'managed-settlement-pending', out.halt && out.halt.message);
+ assert.equal(out.halt.phase, 'preflight');
+ assert.match(out.halt.message, /duplicateRule email: .*no longer declares\. Restore its declaration, with configurationIdentity "stable-v1"/);
+ assert.deepEqual(out.sent, [], 'zero service mutations');
+ assert.ok(h.store.readGroup('duplicateRule', 'email').pending, 'the debt is kept: never retired or reset');
+ }
+ // A committed item the App Spec dropped is no debt: its rows simply stay.
+ const done = await harness();
+ await created(done);
+ const out = await pass(reopen(done), unrelated);
+ assert.equal(out.halt, null, out.halt && out.halt.message);
+ assert.ok(committed(done, 'customApi', 'contoso_calc'), 'its binding is kept');
+});
+
+test('a build whose App Spec declares no configuration item still stops on a pending protected attempt before its first write', async () => {
+ const h = await pendingRule();
+ // No configuration list and no solution version: the build makes no configuration runtime at all.
+ const { configurationIdentity, ...spec } = configSpec({ environmentVariables: [], customApis: [], duplicateDetectionRules: [] });
+ assert.deepEqual(validateAppSpec(spec).errors, []);
+ const mark = h.org.requests.length;
+ let caught;
+ try {
+ await runSdkBuild(spec, { sdk: h.sdk, apply: true, phases: STAGES.data, workspaceDir: makeTempDir('cfg-protected-ws-'), protectedConfiguration: reopen(h).protectedConfiguration, emit: () => {} });
+ } catch (error) {
+ caught = error;
+ }
+ assert.equal(caught && caught.code, 'managed-settlement-pending', caught && caught.message);
+ assert.equal(caught.phase, 'preflight');
+ assert.equal(caught.retry, RETRY.NEVER);
+ assert.deepEqual(h.org.requests.slice(mark).filter((r) => r.method !== 'GET'), [], 'zero service mutations');
+ assert.ok(h.store.readGroup('duplicateRule', 'email').pending);
+});
+
+test('without the opt-in the hookup is ignored: no preflight read, and the plain path creates as before', async () => {
+ const h = await harness();
+ const { configurationIdentity, ...plain } = configSpec();
+ assert.equal(configurationIdentity, 'stable-v1');
+ assert.equal(P.configurationIdentityOf(plain), false);
+ const runtime = createConfigurationRuntime({ spec: plain, sdk: h.sdk, opts: { protectedConfiguration: h.protectedConfiguration }, appUniqueName: 'contoso_configured' });
+ assert.deepEqual(await runtime.preflight(), { halts: [] });
+ assert.deepEqual(h.org.requests, [], 'the preflight read nothing');
+ const out = await pass(h, plain);
+ assert.equal(out.halt, null, out.halt && out.halt.message);
+ assert.ok(!h.store.readGroup('customApi', 'contoso_calc').committed, 'nothing is bound without the opt-in');
+});
+// The first protected create of an item: its namesake query must be read whole and find nothing, else nothing is created.
+const variableOnly = () => configSpec({ customApis: [], duplicateDetectionRules: [] });
+const VARIABLE_ROW = { schemaname: 'contoso_ApiBase', displayname: 'contoso_ApiBase', type: 100000000, defaultvalue: 'https://api.contoso.com' };
+async function insertRow(org, set, row) {
+ const res = await org.request({ url: `${org.origin}/api/data/v9.2/${set}`, method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(row) });
+ assert.ok(res.statusCode < 300, `${set}: ${res.statusCode}`);
+ return /\(([0-9a-f-]{36})\)/i.exec(res.headers['odata-entityid'])[1];
+}
+
+test('a namesake at another id before the first protected create stops it as a conflict: nothing is created or bound', async () => {
+ const h = await harness();
+ const foreign = await insertRow(h.org, 'environmentvariabledefinitions', VARIABLE_ROW);
+ const out = await pass(h, variableOnly());
+ // Judged by the read-only preflight, before any step runs: the build stops before its first write.
+ assert.equal(out.halt && out.halt.code, 'create-identity-conflict', out.halt && out.halt.message);
+ assert.equal(out.halt.phase, 'preflight');
+ assert.match(out.halt.message, new RegExp(`environmentVariable contoso_apibase: .*namesake at another id \\(${foreign}\\)`));
+ assert.equal(out.step, null, 'no step is applied');
+ assert.deepEqual(out.sent, [], 'nothing is sent');
+ assert.deepEqual(h.org.rows('environmentvariabledefinitions').map((r) => r.environmentvariabledefinitionid), [foreign], 'the namesake is not adopted, and nothing is created beside it');
+ const group = h.store.readGroup('environmentVariable', 'contoso_apibase');
+ assert.equal(group.committed, null);
+ assert.equal(group.pending, null);
+});
+
+test('a namesake query that cannot be read whole stops the first protected create unverified: nothing is created', async () => {
+ // The SDK's own name lookup (`$top=2`) answers as usual; the create's complete namesake query answers a first page whose
+ // continuation fails, so it cannot prove there is no namesake on a later page.
+ const h = await harness({ intercept: ({ method, path }) => {
+ if (method !== 'GET' || !path.startsWith('/environmentvariabledefinitions?') || /\$top=/.test(path)) return undefined;
+ if (/\$skiptoken=/.test(path)) return { statusCode: 503, body: { error: { code: '0x80040216', message: 'busy' } } };
+ return { statusCode: 200, body: { value: [], '@odata.nextLink': 'https://contoso.crm.dynamics.com/api/data/v9.0/environmentvariabledefinitions?$select=environmentvariabledefinitionid,schemaname&$skiptoken=1' } };
+ } });
+ const out = await pass(h, variableOnly());
+ assert.equal(out.halt && out.halt.code, 'create-identity-unverified', out.halt && out.halt.message);
+ assert.equal(out.halt.phase, 'preflight');
+ assert.equal(out.step, null, 'no step is applied');
+ assert.ok(h.org.requests.some((r) => /\$skiptoken=/.test(r.path)), 'the continuation was followed');
+ assert.deepEqual(out.sent, [], 'nothing is sent');
+ assert.deepEqual(h.org.rows('environmentvariabledefinitions'), []);
+ assert.equal(h.store.readGroup('environmentVariable', 'contoso_apibase').committed, null);
+});
+
+test('a namesake or a row at the derived id that appears after the preflight is still caught at dispatch: nothing is created or bound', async () => {
+ for (const at of ['namesake', 'derived id']) {
+ const h = await harness();
+ const runtime = createConfigurationRuntime({ spec: variableOnly(), sdk: h.sdk, opts: { protectedConfiguration: h.protectedConfiguration }, appUniqueName: 'contoso_configured' });
+ await runtime.preflight();
+ const mark = h.org.requests.length;
+ // The derived id the preflight read exactly: GET /environmentvariabledefinitions(<id>)?$select=...
+ const derived = h.org.requests.map((r) => /^\/environmentvariabledefinitions\(([0-9a-f-]{36})\)/i.exec(r.path)).find(Boolean)[1];
+ const row = at === 'namesake' ? VARIABLE_ROW : { ...VARIABLE_ROW, environmentvariabledefinitionid: derived };
+ const foreign = await insertRow(h.org, 'environmentvariabledefinitions', row);
+ const step = await runtime.apply('data-model');
+ // The row seeded at the derived id holds a column value this build cannot read, so its exact read is unknown
+ // (unverified); the namesake is a conflict. The preflight of a next build says the same, before any write.
+ const code = at === 'namesake' ? 'create-identity-conflict' : 'create-identity-unverified';
+ assert.deepEqual(step.halt && step.halt.items, [{ kind: 'environmentVariable', key: 'contoso_ApiBase', code }], at);
+ assert.deepEqual(h.org.requests.slice(mark + 1).filter((r) => r.method !== 'GET'), [], `${at}: nothing is sent`);
+ assert.deepEqual(h.org.rows('environmentvariabledefinitions').map((r) => r.environmentvariabledefinitionid), [foreign], `${at}: nothing is created`);
+ assert.equal(h.store.readGroup('environmentVariable', 'contoso_apibase').committed, null, at);
+ const next = await pass(h, variableOnly());
+ assert.equal(next.halt && next.halt.code, code, `${at}: ${next.halt && next.halt.message}`);
+ assert.equal(next.halt.phase, 'preflight', at);
+ assert.deepEqual(next.sent, [], `${at}: the next build sends nothing`);
+ }
+});
+
+test('a create proved never sent meets the same namesake query before the first write; without a namesake it is sent once', async () => {
+ for (const namesake of [true, false]) {
+ const h = await harness();
+ const types = await B.readComponentTypes(h.sdk.dataverse);
+ const planned = B.planOf(variableOnly(), { kind: 'environmentVariable', key: 'contoso_ApiBase', solution: SOL, componentTypes: types.types });
+ // An attempt prepared and never dispatched: its recovery proves nothing was sent, so the rerun sends it again.
+ h.ctx.begin([planned.plan]);
+ const foreign = namesake ? await insertRow(h.org, 'environmentvariabledefinitions', VARIABLE_ROW) : null;
+ const out = await pass(reopen(h), variableOnly());
+ if (namesake) {
+ assert.equal(out.halt && out.halt.code, 'create-identity-conflict', out.halt && out.halt.message);
+ assert.equal(out.halt.phase, 'preflight');
+ assert.deepEqual(out.sent, [], 'nothing is sent');
+ assert.deepEqual(h.org.rows('environmentvariabledefinitions').map((r) => r.environmentvariabledefinitionid), [foreign]);
+ assert.ok(h.store.readGroup('environmentVariable', 'contoso_apibase').pending, 'the attempt stays pending');
+ } else {
+ assert.equal(out.halt, null, out.halt && `${out.halt.code}: ${out.halt.message}`);
+ assert.deepEqual(out.sent.filter((r) => r.path.startsWith('/environmentvariabledefinitions')).map((r) => r.method), ['POST'], 'sent once');
+ assert.ok(committed(h, 'environmentVariable', 'contoso_apibase'));
+ }
+ }
+});
+
+test('clearing a protected variable\'s value would delete its value row: even authorized, it stops in preflight with nothing sent', async () => {
+ const spec = variableOnly();
+ const valueOf = (Value) => readDeploymentBindings({ EnvironmentVariables: [{ SchemaName: 'contoso_ApiBase', Value }] }, spec);
+ const authorizedDestructive = new Set(['environmentVariableValue:contoso_apibase:value']);
+ const h = await harness();
+ const first = await pass(h, spec, { configurationBindings: valueOf('https://one.contoso.com') });
+ assert.equal(first.halt, null, first.halt && `${first.halt.code}: ${first.halt.message}`);
+ const [valueRow] = h.org.rows('environmentvariablevalues');
+ assert.ok(valueRow, 'the value was created');
+ const cleared = await pass(h, spec, { configurationBindings: valueOf(null), authorizedDestructive });
+ assert.equal(cleared.halt && cleared.halt.code, 'configuration-protected-removal-unsupported', cleared.halt && cleared.halt.message);
+ assert.equal(cleared.halt.phase, 'preflight');
+ assert.match(cleared.halt.message, /No service changes were sent by this build/);
+ assert.deepEqual(cleared.sent, [], 'nothing is sent');
+ assert.deepEqual(h.org.rows('environmentvariablevalues').map((r) => r.environmentvariablevalueid), [valueRow.environmentvariablevalueid]);
+ // The neighbours stay: an authorized replacement is made at the bound value row, and a settings entry that leaves the
+ // value alone sends nothing.
+ const replaced = await pass(h, spec, { configurationBindings: valueOf('https://two.contoso.com'), authorizedDestructive });
+ assert.equal(replaced.halt, null, replaced.halt && `${replaced.halt.code}: ${replaced.halt.message}`);
+ assert.deepEqual(replaced.sent.map((r) => r.method), ['PATCH']);
+ assert.deepEqual(h.org.rows('environmentvariablevalues').map((r) => [r.environmentvariablevalueid, r.value]), [[valueRow.environmentvariablevalueid, 'https://two.contoso.com']]);
+ const untouched = await pass(h, spec, { configurationBindings: valueOf('') });
+ assert.equal(untouched.halt, null, untouched.halt && untouched.halt.message);
+ assert.deepEqual(untouched.sent, []);
+ // Without the opt-in an authorized clear deletes the value, as before.
+ const { configurationIdentity, ...plain } = spec;
+ assert.equal(configurationIdentity, 'stable-v1');
+ const p = await harness({ hookup: false });
+ const made = await pass(p, plain, { configurationBindings: valueOf('https://one.contoso.com') });
+ assert.equal(made.halt, null, made.halt && made.halt.message);
+ const legacy = await pass(p, plain, { configurationBindings: valueOf(null), authorizedDestructive });
+ assert.equal(legacy.halt, null, legacy.halt && `${legacy.halt.code}: ${legacy.halt.message}`);
+ assert.deepEqual(legacy.sent.map((r) => r.method), ['DELETE']);
+ assert.deepEqual(p.org.rows('environmentvariablevalues'), []);
+});
+
+test('a first value of a bound protected variable is created at its derived id inside the variable\'s own protected set, and bound', async () => {
+ const h = await harness();
+ const spec = variableOnly();
+ await created(h, spec);
+ const before = committed(h, 'environmentVariable', 'contoso_apibase');
+ const bindings = readDeploymentBindings({ EnvironmentVariables: [{ SchemaName: 'contoso_ApiBase', Value: 'https://one.contoso.com' }] }, spec);
+ const out = await pass(h, spec, { configurationBindings: bindings });
+ assert.equal(out.halt, null, out.halt && `${out.halt.code}: ${out.halt.message}`);
+ assert.deepEqual(out.sent.map((r) => `${r.method} ${r.path.split('?')[0]}`), ['POST /environmentvariablevalues']);
+ const after = committed(h, 'environmentVariable', 'contoso_apibase');
+ assert.equal(after.records.length, before.records.length + 1);
+ const valueRecord = after.records.find((r) => r.kind === 'environmentVariableValue');
+ assert.deepEqual(h.org.rows('environmentvariablevalues').map((r) => r.environmentvariablevalueid), [valueRecord.id]);
+ const again = await pass(reopen(h), spec, { configurationBindings: bindings });
+ assert.equal(again.halt, null, again.halt && again.halt.message);
+ assert.deepEqual(again.sent, []);
+});
+
+test('a protected variable\'s definition edit commits a new proved baseline, and keeps its bound value without sending it', async () => {
+ const h = await harness();
+ const spec = variableOnly();
+ const valueOf = (Value) => readDeploymentBindings({ EnvironmentVariables: [{ SchemaName: 'contoso_ApiBase', Value }] }, spec);
+ await created(h, spec);
+ await created(h, spec, { configurationBindings: valueOf('https://one.contoso.com') });
+ const before = committed(h, 'environmentVariable', 'contoso_apibase');
+ const valueId = before.records.find((r) => r.kind === 'environmentVariableValue').id;
+ // The settings do not name the value this run: the definition edit is made, the value row is neither sent nor dropped.
+ const next = { ...spec, environmentVariables: [{ ...spec.environmentVariables[0], description: 'Updated definition' }] };
+ const out = await pass(h, next);
+ assert.equal(out.halt, null, out.halt && `${out.halt.code}: ${out.halt.message}`);
+ assert.deepEqual(out.sent.map((r) => `${r.method} ${r.path.split('(')[0]}`), ['PATCH /environmentvariabledefinitions']);
+ assert.equal(h.org.rows('environmentvariabledefinitions')[0].description, 'Updated definition');
+ const after = committed(h, 'environmentVariable', 'contoso_apibase');
+ assert.notEqual(after.generation, before.generation, 'the edit is proved and committed as the new baseline');
+ assert.notEqual(after.records[0].intentSha256, before.records[0].intentSha256);
+ assert.equal(after.records.find((r) => r.kind === 'environmentVariableValue').id, valueId, 'the bound value stays bound');
+ assert.deepEqual(h.org.rows('environmentvariablevalues').map((r) => [r.environmentvariablevalueid, r.value]), [[valueId, 'https://one.contoso.com']]);
+ // An authorized replacement of the variable's own value is a conditional PATCH of that row.
+ const authorizedDestructive = new Set(['environmentVariableValue:contoso_apibase:value']);
+ const replaced = await pass(h, next, { configurationBindings: valueOf('https://two.contoso.com'), authorizedDestructive });
+ assert.equal(replaced.halt, null, replaced.halt && `${replaced.halt.code}: ${replaced.halt.message}`);
+ assert.deepEqual(replaced.sent.map((r) => `${r.method} ${r.path.split('?')[0]}`), [`PATCH /environmentvariablevalues(${valueId})`]);
+ assert.match(String(Object.entries(replaced.sent[0].headers).find(([k]) => k.toLowerCase() === 'if-match')?.[1]), /^W\/"\d+"$/);
+ assert.notEqual(committed(h, 'environmentVariable', 'contoso_apibase').generation, after.generation);
+});
+
+test('a value made outside the plugin under a bound protected variable is never overwritten or adopted, authorized or not', async () => {
+ const h = await harness();
+ const spec = variableOnly();
+ await created(h, spec);
+ const rootId = committed(h, 'environmentVariable', 'contoso_apibase').records[0].id;
+ const foreignId = await insertRow(h.org, 'environmentvariablevalues', {
+ value: 'foreign-value-before',
+ '[email protected]': `/environmentvariabledefinitions(${rootId})`,
+ });
+ // A rerun that writes nothing for the variable is not stopped by a value a maker set by hand.
+ const quiet = await pass(reopen(h), spec);
+ assert.equal(quiet.halt, null, quiet.halt && quiet.halt.message);
+ assert.deepEqual(quiet.sent, []);
+ const bindings = readDeploymentBindings({ EnvironmentVariables: [{ SchemaName: 'contoso_ApiBase', Value: 'current-value-after' }] }, spec);
+ const authorizedDestructive = new Set(['environmentVariableValue:contoso_apibase:value']);
+ for (const opts of [{ configurationBindings: bindings, authorizedDestructive }, { configurationBindings: bindings }]) {
+ const out = await pass(reopen(h), spec, opts);
+ assert.equal(out.halt && out.halt.code, 'create-identity-conflict', out.halt && out.halt.message);
+ assert.equal(out.halt.phase, 'preflight');
+ assert.deepEqual(out.sent, []);
+ }
+ // A definition edit would write the variable too: the row it does not hold still stops it.
+ const edited = await pass(reopen(h), { ...spec, environmentVariables: [{ ...spec.environmentVariables[0], description: 'Edited' }] });
+ assert.equal(edited.halt && edited.halt.code, 'create-identity-conflict', edited.halt && edited.halt.message);
+ assert.deepEqual(edited.sent, []);
+ // The write itself is held to the plan made from fresh reads (its create set admits only the rows the plan holds): a
+ // step run without the preflight still never PATCHes a value row the binding does not hold.
+ const runtime = createConfigurationRuntime({ spec, sdk: h.sdk, opts: { protectedConfiguration: reopen(h).protectedConfiguration, configurationBindings: bindings, authorizedDestructive }, appUniqueName: 'contoso_configured' });
+ const mark = h.org.requests.length;
+ const step = await runtime.apply('data-model').catch((error) => ({ error }));
+ assert.ok(step.error || JSON.stringify(step).includes('create-identity-conflict'), JSON.stringify(step).slice(0, 400));
+ assert.deepEqual(h.org.requests.slice(mark).filter((r) => r.method !== 'GET'), []);
+ assert.deepEqual(h.org.rows('environmentvariablevalues').map((r) => [r.environmentvariablevalueid, r.value]), [[foreignId, 'foreign-value-before']]);
+ assert.equal(committed(h, 'environmentVariable', 'contoso_apibase').records.length, 1, 'nothing is adopted');
+});
+
+// A pending edit of a bound item, judged from what its attempt persisted. `lostAfterApply` answers the Custom API PATCH with a
+// failure after the org applied it (an answer lost after the change); `refuse` answers it with a failure the org never applied.
+function editHarness() {
+ const mode = { now: null };
+ let org;
+ const ready = harness({ intercept: async (req) => {
+ if (!mode.now || req.method !== 'PATCH' || !req.path.startsWith('/customapis(')) return undefined;
+ const how = mode.now;
+ mode.now = null;
+ if (how === 'lostAfterApply') await org.request({ url: `${org.origin}/api/data/v9.0${req.path}`, method: req.method, headers: req.headers, body: JSON.stringify(req.body) });
+ return { statusCode: 400, body: { error: { code: '0x80040216', message: 'the answer was lost' } } };
+ } }).then((h) => { org = h.org; return h; });
+ return { ready, mode };
+}
+const apiSpec = (over = {}) => configSpec({ environmentVariables: [], duplicateDetectionRules: [], ...over });
+// The edit a build would begin for the bound Custom API (as the port's locate plans it), begun here and never sent.
+async function beginUnsentApiEdit(h, spec) {
+ const types = await B.readComponentTypes(h.sdk.dataverse);
+ const group = committed(h, 'customApi', 'contoso_calc');
+ const bases = new Map();
+ for (const r of group.records) bases.set(r.id, await B.readConfigurationRow(h.sdk.dataverse, r.kind, r.id));
+ const root = group.records.find((r) => r.kind === 'customApi');
+ const planned = B.planOf(spec, { kind: 'customApi', key: 'contoso_Calc', solution: SOL, componentTypes: types.types, bases,
+ boundSlots: ['request:a', 'response:r'], baseGeneration: group.generation, boundIdOf: (k) => (k === 'customApi' ? root.id : undefined) });
+ const [attempt] = h.ctx.begin([planned.plan]);
+ return { attempt, rootId: root.id };
+}
+
+test('a protected Custom API edit whose answer was lost after it applied commits read-only on the rerun: nothing is sent again', async () => {
+ const { ready, mode } = editHarness();
+ const h = await ready;
+ await created(h, apiSpec());
+ const before = committed(h, 'customApi', 'contoso_calc');
+ const edited = apiSpec(api({ description: 'Edited once' }));
+ mode.now = 'lostAfterApply';
+ const first = await pass(h, edited);
+ assert.ok(first.halt, 'the lost answer stops the build');
+ assert.ok(h.store.readGroup('customApi', 'contoso_calc').pending, 'the edit is kept pending');
+ assert.equal(h.org.rows('customapis')[0].description, 'Edited once');
+ assertCopyStop(await pass(reopen(h), edited), 'customApi', 'contoso_calc');
+ const again = await pass(reopen(h), edited, overwriteCopy('customApi', 'contoso_calc'));
+ assert.equal(again.halt, null, again.halt && `${again.halt.code}: ${again.halt.message}`);
+ assert.deepEqual(again.sent, [], 'the edit is proved from its own expectation, never sent twice');
+ const group = h.store.readGroup('customApi', 'contoso_calc');
+ assert.equal(group.pending, null);
+ assert.notEqual(group.committed.generation, before.generation, 'the proved edit is the new baseline');
+ assert.equal(group.committed.records.find((r) => r.kind === 'customApi').id, before.records.find((r) => r.kind === 'customApi').id);
+ assert.deepEqual((await pass(reopen(h), edited)).sent, []);
+});
+
+test('a protected Custom API edit refused by the org stays owed: the rerun never replays it and nothing is sent', async () => {
+ const { ready, mode } = editHarness();
+ const h = await ready;
+ await created(h, apiSpec());
+ const edited = apiSpec(api({ description: 'Edited once' }));
+ mode.now = 'refuse';
+ assert.ok((await pass(h, edited)).halt);
+ assert.notEqual(h.org.rows('customapis')[0].description, 'Edited once', 'the org never applied it');
+ assertCopyStop(await pass(reopen(h), edited), 'customApi', 'contoso_calc');
+ // Replacing the copy is not consent to replay: the edit stays owed with the approval given, run after run.
+ for (let i = 0; i < 2; i += 1) {
+ const again = await pass(reopen(h), edited, overwriteCopy('customApi', 'contoso_calc'));
+ assert.ok(again.halt, 'an edit that may have been sent is never replayed');
+ assert.notEqual(again.halt.code, 'workspace-copy-unsent-edits', again.halt.message);
+ assert.deepEqual(again.sent, []);
+ assert.ok(h.store.readGroup('customApi', 'contoso_calc').pending, 'its debt is kept');
+ }
+});
+
+test('a protected Custom API edit proved unsent is resumed under its own attempt and sent exactly once', async () => {
+ const h = await harness();
+ await created(h, apiSpec());
+ const edited = apiSpec(api({ description: 'Edited once' }));
+ const { attempt, rootId } = await beginUnsentApiEdit(h, edited);
+ assert.equal(h.store.readGroup('customApi', 'contoso_calc').pending.token, attempt.token);
+ const out = await pass(reopen(h), edited);
+ assert.equal(out.halt, null, out.halt && `${out.halt.code}: ${out.halt.message}`);
+ assert.deepEqual(out.sent.map((r) => `${r.method} ${r.path.split('?')[0]}`), [`PATCH /customapis(${rootId})`]);
+ assert.equal(h.org.rows('customapis')[0].description, 'Edited once');
+ assert.equal(h.store.readGroup('customApi', 'contoso_calc').pending, null);
+ assert.deepEqual((await pass(reopen(h), edited)).sent, [], 'settled: the rerun sends nothing');
+});
+
+test('an unsent protected Custom API edit whose declaration then changed is not sent: it stays owed until restored', async () => {
+ const h = await harness();
+ await created(h, apiSpec());
+ const edited = apiSpec(api({ description: 'Edited once' }));
+ await beginUnsentApiEdit(h, edited);
+ const other = await pass(reopen(h), apiSpec(api({ description: 'Edited twice' })));
+ assert.equal(other.halt && other.halt.code, 'managed-pending-intent-changed');
+ assert.deepEqual(other.sent, []);
+ assert.ok(h.store.readGroup('customApi', 'contoso_calc').pending);
+ const restored = await pass(reopen(h), edited);
+ assert.equal(restored.halt, null, restored.halt && `${restored.halt.code}: ${restored.halt.message}`);
+ assert.equal(restored.sent.length, 1);
+});
+
+test('an unsent protected value edit already at its target asks for the exact approval of its private value: never reported unchanged while it is owed', async () => {
+ const h = await harness();
+ const spec = variableOnly();
+ const bindings = (Value) => readDeploymentBindings({ EnvironmentVariables: [{ SchemaName: 'contoso_ApiBase', Value }] }, spec);
+ await created(h, spec, { configurationBindings: bindings('old-input') });
+ const group = committed(h, 'environmentVariable', 'contoso_apibase');
+ const types = await B.readComponentTypes(h.sdk.dataverse);
+ const bases = new Map();
+ for (const row of group.records) bases.set(row.id, await B.readConfigurationRow(h.sdk.dataverse, row.kind, row.id));
+ const root = group.records.find((r) => r.kind === 'environmentVariable');
+ const child = group.records.find((r) => r.kind === 'environmentVariableValue');
+ const next = bindings('next-input');
+ const planned = B.planOf(spec, { kind: 'environmentVariable', key: 'contoso_ApiBase', solution: SOL, bindings: next,
+ componentTypes: types.types, bases, boundSlots: ['value'], baseGeneration: group.generation, boundIdOf: () => root.id });
+ h.ctx.begin([planned.plan]);
+ // The target is made outside the plugin: the prepared edit has nothing left to write, but its private value is not the
+ // plugin's own until the maker approves it.
+ const manual = await h.org.request({ url: `${h.org.origin}/api/data/v9.0/environmentvariablevalues(${child.id})`, method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value: 'next-input' }) });
+ assert.ok(manual.statusCode < 300);
+ const destructive = new Set(['environmentVariableValue:contoso_apibase:value']);
+ const out = await pass(reopen(h), spec, { configurationBindings: next, authorizedDestructive: destructive });
+ assert.equal(out.halt && out.halt.code, 'create-ownership-required', out.halt && out.halt.message);
+ assert.match(out.halt.message, /given after checking those rows are yours: "adopt:environmentVariableValue:contoso_apibase\/value"\.$/);
+ assert.deepEqual(out.sent, []);
+ const held = h.store.readGroup('environmentVariable', 'contoso_apibase');
+ assert.ok(held.pending, 'the attempt stays owed');
+ assert.equal(held.committed.generation, group.generation);
+ // Without the preflight, the plan's own resolve stops on the same verdict: nothing is planned as unchanged.
+ const runtime = createConfigurationRuntime({ spec, sdk: h.sdk, opts: { protectedConfiguration: reopen(h).protectedConfiguration, configurationBindings: next, authorizedDestructive: destructive }, appUniqueName: 'contoso_configured' });
+ const mark = h.org.requests.length;
+ const step = await runtime.apply('data-model');
+ assert.deepEqual(step.halt && step.halt.items.map(({ kind, code }) => `${kind} ${code}`), ['environmentVariable create-ownership-required']);
+ assert.deepEqual(step.outcome.unchanged || [], []);
+ assert.deepEqual(h.org.requests.slice(mark).filter((r) => r.method !== 'GET'), []);
+ assert.ok(h.store.readGroup('environmentVariable', 'contoso_apibase').pending);
+ // The exact approval accepts the same attempt read-only: nothing is sent.
+ const approved = await pass(reopen(h, ['adopt:environmentVariableValue:contoso_apibase/value']), spec, { configurationBindings: next, authorizedDestructive: destructive });
+ assert.equal(approved.halt, null, approved.halt && `${approved.halt.code}: ${approved.halt.message}`);
+ assert.deepEqual(approved.sent, []);
+ assert.equal(h.store.readGroup('environmentVariable', 'contoso_apibase').pending, null);
+});
+
+test('an unsent protected edit already at its target whose solution membership is gone stops: no membership is added outside its attempt', async () => {
+ const h = await harness();
+ await created(h, apiSpec());
+ const target = apiSpec(api({ description: 'Target already present' }));
+ const { rootId } = await beginUnsentApiEdit(h, target);
+ const manual = await h.org.request({ url: `${h.org.origin}/api/data/v9.0/customapis(${rootId})`, method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ description: 'Target already present' }) });
+ assert.ok(manual.statusCode < 300);
+ const membership = h.org.rows('solutioncomponents').find((r) => r.objectid === rootId);
+ assert.ok(membership);
+ const deleted = await h.org.request({ url: `${h.org.origin}/api/data/v9.0/solutioncomponents(${membership.solutioncomponentid})`, method: 'DELETE', headers: {} });
+ assert.ok(deleted.statusCode < 300);
+ const out = await pass(reopen(h), target);
+ assert.equal(out.halt && out.halt.code, 'create-completion-required', out.halt && out.halt.message);
+ assert.deepEqual(out.sent, []);
+ assert.ok(h.store.readGroup('customApi', 'contoso_calc').pending, 'the attempt stays owed');
+ // Without the preflight: the same verdict from resolve, and no AddSolutionComponent.
+ const runtime = createConfigurationRuntime({ spec: target, sdk: h.sdk, opts: { protectedConfiguration: reopen(h).protectedConfiguration }, appUniqueName: 'contoso_configured' });
+ const mark = h.org.requests.length;
+ const step = await runtime.apply('data-model');
+ assert.deepEqual(step.halt && step.halt.items.map(({ kind, code }) => `${kind} ${code}`), ['customApi create-completion-required']);
+ assert.deepEqual(h.org.requests.slice(mark).filter((r) => r.method !== 'GET'), []);
+ assert.ok(h.store.readGroup('customApi', 'contoso_calc').pending);
+});
+
+test('an unsent protected edit whose solution membership is gone adds it only inside its own attempt, after its write', async () => {
+ const h = await harness();
+ await created(h, apiSpec());
+ const edited = apiSpec(api({ description: 'Edited once' }));
+ const { rootId } = await beginUnsentApiEdit(h, edited);
+ const membership = h.org.rows('solutioncomponents').find((r) => r.objectid === rootId);
+ const deleted = await h.org.request({ url: `${h.org.origin}/api/data/v9.0/solutioncomponents(${membership.solutioncomponentid})`, method: 'DELETE', headers: {} });
+ assert.ok(deleted.statusCode < 300);
+ const runtime = createConfigurationRuntime({ spec: edited, sdk: h.sdk, opts: { protectedConfiguration: reopen(h).protectedConfiguration }, appUniqueName: 'contoso_configured' });
+ const mark = h.org.requests.length;
+ const step = await runtime.apply('data-model');
+ assert.equal(step.halt, null, step.halt && JSON.stringify(step.halt.items));
+ assert.deepEqual(h.org.requests.slice(mark).filter((r) => r.method !== 'GET').map((r) => `${r.method} ${r.path.split('?')[0]}`),
+ [`PATCH /customapis(${rootId})`, 'POST /AddSolutionComponent']);
+ assert.equal(h.store.readGroup('customApi', 'contoso_calc').pending, null);
+});
+
+test('an unsent protected first value whose row was made at its id outside the plugin is never planned unchanged while its create is owed', async () => {
+ const h = await harness();
+ const spec = variableOnly();
+ await created(h, spec);
+ const group = committed(h, 'environmentVariable', 'contoso_apibase');
+ const types = await B.readComponentTypes(h.sdk.dataverse);
+ const bases = new Map();
+ for (const row of group.records) bases.set(row.id, await B.readConfigurationRow(h.sdk.dataverse, row.kind, row.id));
+ const root = group.records.find((r) => r.kind === 'environmentVariable');
+ const next = readDeploymentBindings({ EnvironmentVariables: [{ SchemaName: 'contoso_ApiBase', Value: 'https://one.contoso.com' }] }, spec);
+ const planned = B.planOf(spec, { kind: 'environmentVariable', key: 'contoso_ApiBase', solution: SOL, bindings: next,
+ componentTypes: types.types, bases, boundSlots: [], baseGeneration: group.generation, boundIdOf: () => root.id });
+ const valueRow = planned.plan.rows.find((r) => r.kind === 'environmentVariableValue');
+ assert.equal(valueRow.mode, 'create');
+ h.ctx.begin([planned.plan]);
+ const manual = await h.org.request({ url: `${h.org.origin}/api/data/v9.0/environmentvariablevalues`, method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ environmentvariablevalueid: valueRow.id, value: 'https://one.contoso.com', schemaname: 'contoso_ApiBase', '[email protected]': `/environmentvariabledefinitions(${root.id})` }) });
+ assert.ok(manual.statusCode < 300, String(manual.statusCode));
+ // Without the preflight, the plan's own resolve says the create is owed: the item is neither unchanged nor written.
+ const runtime = createConfigurationRuntime({ spec, sdk: h.sdk, opts: { protectedConfiguration: reopen(h).protectedConfiguration, configurationBindings: next }, appUniqueName: 'contoso_configured' });
+ const mark = h.org.requests.length;
+ const step = await runtime.apply('data-model');
+ assert.deepEqual(step.halt && step.halt.items.map(({ kind, code }) => `${kind} ${code}`), ['environmentVariable create-completion-required']);
+ assert.deepEqual(step.outcome.unchanged || [], []);
+ assert.deepEqual(h.org.requests.slice(mark).filter((r) => r.method !== 'GET'), []);
+ assert.ok(h.store.readGroup('environmentVariable', 'contoso_apibase').pending);
+});
+
+test('a bound protected item whose workspace copy differs from the server\'s is never read over: build and verify stop, and only its exact overwrite approval replaces it', async () => {
+ const h = await harness();
+ const spec = apiSpec();
+ await created(h, spec);
+ const before = committed(h, 'customApi', 'contoso_calc');
+ const id = before.records.find((r) => r.kind === 'customApi').id;
+ await h.sdk.updateElement('customApi', id, '/description', 'Retained maker draft');
+ const { hasUnsyncedEdits } = require('../lib/unsynced-edits.js');
+ const dirty = () => hasUnsyncedEdits(h.sdk, 'customApi', id);
+ assert.equal(await dirty(), true);
+ const out = await pass(reopen(h), spec);
+ assertCopyStop(out, 'customApi', 'contoso_calc');
+ assert.match(out.halt.message, /local copy of the customApi "contoso_calc" .* the copy was kept\. Put any change you want to keep into the App Spec, then approve replacing the local copy with the server's: --authorize overwrite:customApi:contoso_calc/);
+ assert.equal(await dirty(), true, 'the draft is kept');
+ // Without the preflight, the plan's own exact read stops on it too (typed, the id named), before any fetch over it.
+ const runtime = createConfigurationRuntime({ spec, sdk: h.sdk, opts: { protectedConfiguration: reopen(h).protectedConfiguration }, appUniqueName: 'contoso_configured' });
+ const mark = h.org.requests.length;
+ const step = await runtime.apply('data-model');
+ assert.deepEqual(step.halt && step.halt.items.map(({ kind, code }) => `${kind} ${code}`), ['customApi create-completion-required']);
+ assert.deepEqual(h.org.requests.slice(mark).filter((r) => r.method !== 'GET'), []);
+ assert.equal(await dirty(), true);
+ // Verify reads it at its exact id too, and does not read over the draft either.
+ const checks = await readerFor(h.sdk, 'contoso_configured').configuration(spec, undefined, managedManifestView(h.store.snapshot()));
+ assert.equal(checks.find((c) => c.kind === 'customApi' && c.name === 'definition').code, 'create-completion-required');
+ assert.equal(await dirty(), true);
+ assert.deepEqual(committed(h, 'customApi', 'contoso_calc'), before, 'the binding is kept as it was');
+ // An approval for another item, or another family's key of the same spelling, replaces nothing.
+ assertCopyStop(await pass(reopen(h), spec, { authorizedOverwrite: new Set(['customApi:contoso_other', 'view:contoso_calc', 'environmentVariable:contoso_calc']) }), 'customApi', 'contoso_calc');
+ assert.equal(await dirty(), true);
+ // A blanket programmatic `true` names no item, so it approves no replacement either.
+ assertCopyStop(await pass(reopen(h), spec, { authorizedOverwrite: true }), 'customApi', 'contoso_calc');
+ assert.equal(await dirty(), true, 'a blanket boolean never discards the draft');
+ // The maker's decision, the exact approval: the copy is replaced with the server's, and the build goes on and sends
+ // nothing for an unchanged item.
+ const again = await pass(reopen(h), spec, overwriteCopy('customApi', 'contoso_calc'));
+ assert.equal(again.halt, null, again.halt && `${again.halt.code}: ${again.halt.message}`);
+ assert.deepEqual(again.sent, []);
+ assert.equal(await dirty(), false);
+ assert.notEqual(h.org.rows('customapis')[0].description, 'Retained maker draft', 'the draft was never sent');
+ assert.deepEqual((await pass(reopen(h), spec)).sent, []);
+});
+
+// A protected edit the org refuses, with a local edit written into the shared workspace copy at some point of the
+// build's own send. `inject(h, id, sdk)` installs the edit; answers the harness, the root id and the edited App Spec.
+async function refusedSendWith(inject) {
+ let reject = false;
+ const h = await harness({ intercept: ({ method, path }) => (reject && method === 'PATCH' && path.startsWith('/customapis(')
+ ? { statusCode: 400, body: { error: { code: '0x80040216', message: 'refused edit' } } } : undefined) });
+ await created(h, apiSpec());
+ const id = committed(h, 'customApi', 'contoso_calc').records.find((r) => r.kind === 'customApi').id;
+ const state = inject(h, id, { update: h.sdk.updateElement.bind(h.sdk), push: h.sdk.pushArtifact.bind(h.sdk), diff: h.sdk.diffArtifact.bind(h.sdk) });
+ reject = true;
+ const edited = apiSpec(api({ description: 'Build-owned edit' }));
+ const out = await pass(h, edited);
+ return { h, id, edited, out, state };
+}
+const holds = async (h, id, text) => JSON.stringify(await h.sdk.diffArtifact('customApi', id)).includes(text);
+// The kept copy stops every later build before anything is sent, the maker's edit still in it; only the maker's exact
+// approval replaces it, and the refused edit is then recovered from what its attempt persisted: never replayed. `unsent`:
+// the attempt never left (the gate refused its push before dispatch), so the approved build sends it once, its first send.
+async function assertKeptUntilApproved(h, id, edited, text, { unsent = false } = {}) {
+ for (let i = 0; i < 2; i += 1) {
+ assertCopyStop(await pass(reopen(h), edited), 'customApi', 'contoso_calc');
+ assert.ok(await holds(h, id, text), `the local edit "${text}" survives build ${i + 2}`);
+ }
+ const approved = await pass(reopen(h), edited, overwriteCopy('customApi', 'contoso_calc'));
+ assert.ok(approved.halt, 'the refused edit stays owed');
+ assert.notEqual(approved.halt.code, 'workspace-copy-unsent-edits', approved.halt.message);
+ assert.deepEqual(approved.sent.map((r) => `${r.method} ${r.path.split('?')[0]}`), unsent ? [`PATCH /customapis(${id})`] : [], 'replacing the copy sends nothing, and the edit is never replayed');
+ assert.equal(await holds(h, id, text), false, 'the copy was replaced, as the maker approved');
+ assert.ok(h.store.readGroup('customApi', 'contoso_calc').pending, 'its debt is kept');
+}
+
+test('a failed protected send keeps the whole workspace copy: a local edit written while the push was pending survives, and the next build stops with the overwrite approval', async () => {
+ const { h, id, edited, out, state } = await refusedSendWith((h, id, sdk) => {
+ const state = { injected: false };
+ h.sdk.pushArtifact = async (...args) => {
+ const result = await sdk.push(...args);
+ if (!state.injected && args[0] === 'customApi') {
+ await h.sdk.updateElement('customApi', id, '/displayName', 'Maker draft arrived during push');
+ state.injected = true;
+ }
+ return result;
+ };
+ return state;
+ });
+ assert.ok(state.injected);
+ assert.ok(out.halt);
+ assert.equal(out.sent.length, 1);
+ assert.ok(await holds(h, id, 'Maker draft arrived during push'), 'the edit the build did not make is kept');
+ assert.ok(await holds(h, id, 'Build-owned edit'), 'the build\'s own unsent change is kept with it: the copy is never reset');
+ await assertKeptUntilApproved(h, id, edited, 'Maker draft arrived during push');
+});
+
+test('a local edit made while the build prepares its protected send is never taken for the build\'s own: the failed send keeps it', async () => {
+ const { h, id, edited, out, state } = await refusedSendWith((h, id, sdk) => {
+ const state = { injected: false };
+ // The maker's edit lands between the build's own element updates and its push, through the same SDK.
+ h.sdk.updateElement = async (...args) => {
+ const value = await sdk.update(...args);
+ if (!state.injected && args[0] === 'customApi' && args[2] === '/description') {
+ await sdk.update('customApi', id, '/displayName', 'Maker draft before capture');
+ state.injected = true;
+ }
+ return value;
+ };
+ return state;
+ });
+ assert.ok(state.injected);
+ assert.ok(out.halt);
+ // The push now carries a field the build's plan does not hold (the maker's), so the gate refuses it before it leaves.
+ assert.deepEqual(out.sent, [], 'the maker\'s field is never sent under the build\'s attempt');
+ assert.ok(await holds(h, id, 'Maker draft before capture'), 'the maker\'s edit survives the failed send');
+ await assertKeptUntilApproved(h, id, edited, 'Maker draft before capture', { unsent: true });
+});
+
+test('a local edit made after a failed protected send, while a build compares the copy, survives: the next build stops with the overwrite approval', async () => {
+ const { h, id, edited, out, state } = await refusedSendWith((h, id, sdk) => {
+ const state = { failed: false, injected: false };
+ h.sdk.pushArtifact = async (...args) => {
+ try {
+ return await sdk.push(...args);
+ } finally {
+ if (args[0] === 'customApi') state.failed = true;
+ }
+ };
+ // The maker's edit lands just after the first comparison of the copy that follows the failed send — the
+ // diff is not locked, so nothing a comparison answered can be relied on once it has returned.
+ h.sdk.diffArtifact = async (...args) => {
+ const diff = await sdk.diff(...args);
+ if (state.failed && !state.injected && args[0] === 'customApi') {
+ await sdk.update('customApi', id, '/displayName', 'Maker draft after comparison');
+ state.injected = true;
+ }
+ return diff;
+ };
+ return state;
+ });
+ assert.ok(out.halt);
+ assertCopyStop(await pass(reopen(h), edited), 'customApi', 'contoso_calc');
+ assert.ok(state.injected, 'the edit landed after a comparison of the copy');
+ assert.ok(await holds(h, id, 'Maker draft after comparison'), 'the maker\'s edit survives');
+ await assertKeptUntilApproved(h, id, edited, 'Maker draft after comparison');
+});
+
+test('a failed protected send never removes its copy, and an approved replacement that cannot read the server\'s row keeps it and stops', async () => {
+ let denyRead = false;
+ const h = await harness({ intercept: ({ method, path }) => {
+ if (method === 'POST' && path.startsWith('/customapis')) return { statusCode: 400, body: { error: { code: '0x80040216', message: 'refused create' } } };
+ if (denyRead && method === 'GET' && path.startsWith('/customapis(')) return { statusCode: 403, body: { error: { code: '0x80040220', message: 'read denied' } } };
+ return undefined;
+ } });
+ const spec = apiSpec();
+ const fetch = h.sdk.fetchArtifact.bind(h.sdk);
+ // Every read of the Custom API into the workspace is refused, as a denied or failed read would be.
+ h.sdk.fetchArtifact = async (kind, ...rest) => {
+ if (kind === 'customApi') { const e = new Error('read denied'); e.code = 'HTTP_403'; throw e; }
+ return fetch(kind, ...rest);
+ };
+ const out = await pass(h, spec);
+ assert.ok(out.halt);
+ const listed = async () => (await h.sdk.listArtifacts('customApi')).map((s) => s.id);
+ assert.equal((await listed()).length, 1, 'the copy of the refused create is kept, not deleted on a read that proves nothing');
+ assertCopyStop(await pass(reopen(h), spec), 'customApi', 'contoso_calc');
+ // Approved, but the server's row cannot be read: nothing proves what to put in the copy's place, so it is kept.
+ denyRead = true;
+ const unread = await pass(reopen(h), spec, overwriteCopy('customApi', 'contoso_calc'));
+ assert.equal(unread.halt && unread.halt.code, 'workspace-copy-unsent-edits', unread.halt && unread.halt.message);
+ assert.match(unread.halt.message, /could not be replaced with the server's as approved/);
+ assert.deepEqual(unread.sent, []);
+ assert.equal((await listed()).length, 1);
+ // Approved, and the row is proved absent (the create was never taken): the local copy is all there is, and it goes.
+ denyRead = false;
+ const approved = await pass(reopen(h), spec, overwriteCopy('customApi', 'contoso_calc'));
+ assert.ok(!approved.halt || approved.halt.code !== 'workspace-copy-unsent-edits', approved.halt && approved.halt.message);
+});
+// A rule create whose content the service saved and acknowledged, with its solution membership complete, whose initial
+// publication was never dispatched (the process that saved it stopped before the publish left). `settle: true` is what
+// the build's own create set does next (it records the children this process saw created); without it, an earlier
+// process's answers are gone and nothing persisted proves the conditions this plugin's own.
+const publishes = (requests) => requests.filter((r) => /PublishDuplicateRule$/.test(r.path));
+const ruleOnly = () => configSpec({ environmentVariables: [], customApis: [] });
+async function savedUnpublishedRule(h, { settle }) {
+ const types = await B.readComponentTypes(h.sdk.dataverse);
+ const planned = B.planOf(ruleOnly(), { kind: 'duplicateRule', key: 'email', solution: SOL, componentTypes: types.types });
+ const [attempt] = h.ctx.begin([planned.plan]);
+ const classify = B.createSetClassifier([{ token: attempt.token, planned }]);
+ const artifact = B.artifactFor(planned);
+ artifact.status = 'unpublished';
+ const saved = await h.ctx.run({ attempts: [attempt], classify, deleteCode: B.DELETE_CODE, acceptResult: B.acceptResultFor(planned) }, async () => {
+ await h.sdk.createArtifact('duplicateRule', artifact);
+ return h.sdk.pushArtifact('duplicateRule', planned.rows[0].id);
+ });
+ assert.equal(saved.checked, true, 'the content was saved and acknowledged');
+ const absent = (await B.observe(h.sdk.dataverse, planned)).members.filter((m) => m.state === 'absent');
+ await h.ctx.run({ attempts: [attempt], classify, deleteCode: B.DELETE_CODE }, async () => {
+ for (const m of absent) {
+ const want = planned.plan.members.find((x) => x.id === m.id);
+ await h.sdk.dataverse.post('/AddSolutionComponent', { ComponentId: m.id, ComponentType: want.componentType, SolutionUniqueName: SOL, AddRequiredComponents: false });
+ }
+ });
+ if (settle) {
+ const [settled] = h.ctx.settle([{ token: attempt.token, observation: await B.observe(h.sdk.dataverse, planned) }]);
+ assert.equal(settled.verdict.code, 'create-completion-required');
+ }
+ const pending = h.store.readGroup('duplicateRule', 'email').pending;
+ assert.equal(pending.acknowledgedRoot, true);
+ assert.deepEqual(pending.rowProtocol.effects.filter((e) => e.kind === 'rule-state').map((e) => e.dispatched), [false], 'the publication never left');
+ assert.equal(publishes(h.org.requests).length, 0);
+ return { ruleId: planned.rows[0].id, token: attempt.token };
+}
+
+test('a saved rule create whose initial publication never left is published once by the rerun, then bound; nothing is sent again', async () => {
+ const h = await harness();
+ const { ruleId } = await savedUnpublishedRule(h, { settle: true });
+ const later = reopen(h);
+ const out = await pass(later, ruleOnly());
+ assert.equal(out.halt, null, out.halt && `${out.halt.code}: ${out.halt.message}`);
+ assert.deepEqual(out.sent.map((r) => r.path.split('?')[0]), [`/duplicaterules(${ruleId})/Microsoft.Dynamics.CRM.PublishDuplicateRule`], 'only the owed publication, once');
+ assert.equal(h.org.rows('duplicaterules').find((r) => r.duplicateruleid === ruleId).statecode, 1);
+ assert.ok(committed(h, 'duplicateRule', 'email').records.some((r) => r.id === ruleId));
+ const rerun = await pass(later, ruleOnly());
+ assert.equal(rerun.halt, null);
+ assert.deepEqual(rerun.sent, []);
+});
+
+test('an unsent rule publication whose conditions no persisted answer proves asks for their approval before anything is sent, then is sent once', async () => {
+ const h = await harness();
+ await savedUnpublishedRule(h, { settle: false });
+ const asked = await pass(reopen(h), ruleOnly());
+ assert.equal(asked.halt && asked.halt.code, 'create-ownership-required', asked.halt && asked.halt.message);
+ assert.deepEqual(asked.sent, [], 'nothing is published before every row is proved this plugin\'s own');
+ const quoted = /given after checking those rows are yours: (.*)\.$/.exec(asked.halt.message);
+ assert.ok(quoted, asked.halt.message);
+ const tokens = JSON.parse(`[${quoted[1]}]`);
+ assert.ok(tokens.length && tokens.every((t) => t.startsWith('adopt:duplicateRuleCondition:')), tokens.join(' '));
+ const approved = reopen(h, tokens);
+ const out = await pass(approved, ruleOnly());
+ assert.equal(out.halt, null, out.halt && `${out.halt.code}: ${out.halt.message}`);
+ assert.equal(publishes(out.sent).length, 1);
+ assert.equal(out.sent.length, 1);
+ assert.deepEqual((await pass(approved, ruleOnly())).sent, []);
+});
+
+test('the one send of an unsent rule publication is fenced: a refused publish stays owed and is never sent again', async () => {
+ let refuse = true;
+ const h = await harness({ intercept: ({ method, path }) => (refuse && method === 'POST' && /PublishDuplicateRule$/.test(path) ? { statusCode: 400, body: { error: { code: '0x80040216', message: 'publish failed' } } } : undefined) });
+ const { ruleId } = await savedUnpublishedRule(h, { settle: true });
+ const first = await pass(reopen(h), ruleOnly());
+ assert.equal(first.halt && first.halt.code, 'configuration-incomplete', first.halt && first.halt.message);
+ assert.match(first.halt.message, /duplicateRule email \(create-completion-required\)/);
+ assert.equal(publishes(first.sent).length, 1, 'sent once');
+ assert.deepEqual(h.store.readGroup('duplicateRule', 'email').pending.rowProtocol.effects.filter((e) => e.kind === 'rule-state').map((e) => e.dispatched), [true]);
+ refuse = false;
+ const again = await pass(reopen(h), ruleOnly());
+ assert.equal(again.halt && again.halt.code, 'create-completion-required');
+ assert.equal(again.halt.phase, 'preflight');
+ assert.deepEqual(again.sent, [], 'a publish that was sent is never replayed');
+ // The maker publishes it under the same id; the next build binds it with nothing sent.
+ await h.org.request({ url: `${h.org.origin}/api/data/v9.2/duplicaterules(${ruleId})/Microsoft.Dynamics.CRM.PublishDuplicateRule`, method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
+ const done = await pass(reopen(h), ruleOnly());
+ assert.equal(done.halt, null, done.halt && `${done.halt.code}: ${done.halt.message}`);
+ assert.deepEqual(done.sent, []);
+});
+
+test('only one claim may send an unsent rule publication: an older claim is refused at dispatch, and a dispatched one is never claimed again', async () => {
+ const h = await harness();
+ const { ruleId, token } = await savedUnpublishedRule(h, { settle: true });
+ const older = h.store.claimUnsentRowEffect({ token, kind: 'rule-state', id: ruleId });
+ const newer = h.store.claimUnsentRowEffect({ token, kind: 'rule-state', id: ruleId });
+ assert.equal(newer.epoch, older.epoch + 1);
+ assert.throws(() => h.store.markRowEffectDispatch({ token, epoch: older.epoch, kind: 'rule-state', id: ruleId }), (e) => e.code === 'managed-settlement-pending');
+ h.store.markRowEffectDispatch({ token, epoch: newer.epoch, kind: 'rule-state', id: ruleId });
+ assert.throws(() => h.store.claimUnsentRowEffect({ token, kind: 'rule-state', id: ruleId }), (e) => e.code === 'managed-settlement-pending');
+ assert.throws(() => h.store.claimUnsentRowEffect({ token, kind: 'membership', id: ruleId }), (e) => e.code === 'managed-not-settled');
+ const out = await pass(reopen(h), ruleOnly());
+ assert.equal(out.halt && out.halt.code, 'create-completion-required');
+ assert.deepEqual(out.sent, []);
+});
+
+test('removing the opt-in does not move protected items back to name lookup: the build stops before any request', async () => {
+ const { configurationIdentity, ...plain } = configSpec();
+ assert.equal(configurationIdentity, 'stable-v1');
+ // Committed bindings.
+ const h = await harness();
+ await created(h);
+ const mark = h.org.requests.length;
+ const out = await pass(h, plain);
+ assert.equal(out.halt && out.halt.code, 'create-identity-opt-in-required', out.halt && out.halt.message);
+ assert.equal(out.halt.phase, 'preflight');
+ assert.equal(out.halt.retry, RETRY.NEVER);
+ assert.match(out.halt.message, /configurationIdentity "stable-v1"/);
+ assert.match(out.halt.message, /No service changes were sent by this build/);
+ assert.deepEqual(h.org.requests.slice(mark), [], 'not even a read');
+ // A pending attempt is an obligation too.
+ const p = await harness({ intercept: ({ method, path }) => (method === 'POST' && /PublishDuplicateRule$/.test(path) ? { statusCode: 400, body: { error: { code: '0x80040216', message: 'publish failed' } } } : undefined) });
+ assert.ok((await pass(p, configSpec())).halt);
+ assert.ok(p.store.readGroup('duplicateRule', 'email').pending);
+ const pmark = p.org.requests.length;
+ const pending = await pass(p, plain);
+ assert.equal(pending.halt && pending.halt.code, 'create-identity-opt-in-required', pending.halt && pending.halt.message);
+ assert.deepEqual(p.org.requests.slice(pmark), []);
+ // An item the store holds nothing for is not held back: a spec that declares only another item builds as before.
+ const other = await pass(h, { ...plain, environmentVariables: [{ schemaName: 'contoso_Other', type: 'string', defaultValue: 'x' }], customApis: [], duplicateDetectionRules: [] });
+ assert.equal(other.halt, null, other.halt && `${other.halt.code}: ${other.halt.message}`);
+});
+
+// ---------------------------------------------------------------------------------------------
+// Verify under the opt-in, as verify-model-app.js reads it: the workspace's binding store, read-only (managedManifestView, as
+// readVerifyManifest answers it), names the one row each protected item is checked at.
+
+const viewOf = (h) => managedManifestView(h.store.snapshot());
+const definitions = (checks) => Object.fromEntries(checks.filter((c) => c.name === 'definition').map((c) => [`${c.kind} ${c.key}`, c.ok ? 'ok' : c.code]));
+const writesSince = (h, mark) => h.org.requests.slice(mark).filter((r) => r.method !== 'GET');
+
+test('verify under the opt-in reads every protected item at the id its binding holds, and a namesake never stands in for a deleted one', async () => {
+ const h = await harness();
+ await created(h);
+ const read = readerFor(h.sdk, 'contoso_configured');
+ let mark = h.org.requests.length;
+ assert.deepEqual(definitions(await read.configuration(configSpec(), undefined, viewOf(h))),
+ { 'environmentVariable contoso_ApiBase': 'ok', 'customApi contoso_Calc': 'ok', 'duplicateRule email': 'ok' });
+ assert.deepEqual(writesSince(h, mark), [], 'verify sends nothing');
+ // The bound variable is deleted outside the plugin, and an identical one made at another id.
+ const id = committed(h, 'environmentVariable', 'contoso_apibase').records.find((r) => r.kind === 'environmentVariable').id;
+ const res = await h.org.request({ url: `${h.org.origin}/api/data/v9.2/environmentvariabledefinitions(${id})`, method: 'DELETE', headers: {} });
+ assert.ok(res.statusCode < 300);
+ await insertRow(h.org, 'environmentvariabledefinitions', VARIABLE_ROW);
+ mark = h.org.requests.length;
+ const { configurationIdentity, ...plain } = configSpec();
+ assert.equal(configurationIdentity, 'stable-v1');
+ assert.equal(definitions(await read.configuration(plain))['environmentVariable contoso_ApiBase'], 'ok', 'name lookup takes the namesake');
+ const checks = await read.configuration(configSpec(), undefined, viewOf(h));
+ assert.deepEqual(definitions(checks), { 'environmentVariable contoso_ApiBase': B.NOT_FOUND_CODE, 'customApi contoso_Calc': 'ok', 'duplicateRule email': 'ok' });
+ assert.deepEqual(writesSince(h, mark), [], 'verify sends nothing');
+});
+
+test('verify under the opt-in never falls back to a name: no binding store, no binding or an unusable one fails, a pending one is named', async () => {
+ const h = await harness();
+ await created(h);
+ const read = readerFor(h.sdk, 'contoso_configured');
+ const all = (code) => ({ 'environmentVariable contoso_ApiBase': code, 'customApi contoso_Calc': code, 'duplicateRule email': code });
+ assert.deepEqual(definitions(await read.configuration(configSpec(), undefined, undefined)), all('create-identity-unverified'), 'no binding store was read');
+ assert.deepEqual(definitions(await read.configuration(configSpec(), undefined, managedManifestView(null))), all('create-identity-unverified'), 'no binding is held');
+ const unusable = managedManifestView(null);
+ unusable.invalid.push({ family: 'store', key: 'managed-bindings', reason: 'unreadable', code: 'managed-binding-store-unreadable' });
+ assert.deepEqual(definitions(await read.configuration(configSpec(), undefined, unusable)), all('create-identity-unverified'), 'an unusable store proves nothing');
+ const pending = viewOf(h);
+ pending.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');
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/creates-port.test.js b/plugins/model-apps/scripts/tests/creates-port.test.js
index e37062b6e..b5c282fe8 100644
--- a/plugins/model-apps/scripts/tests/creates-port.test.js
+++ b/plugins/model-apps/scripts/tests/creates-port.test.js
@@ -233,9 +233,15 @@ test('the spec decides the mode: no createIdentity and no new feature intents is
// so the engine's, the spec gate's and the flow reader's (declared-bpf-io.js) requires of it are gated edges as well. The
// dashboard helper (dashboard-reconcile.js) derives its seed cell ids with creates-identity.js only on a declared dashboard's
// create, and its workspace scope (dashboard-recovery-workspace.js) reads a retained create copy with creates-local.js only for
-// a declared dashboard; each through one lazy accessor, so those edges are gated too. Apart
+// a declared dashboard; each through one lazy accessor, so those edges are gated too. Verify (verify-model-app.js, which the
+// build requires for its inline --verify) requires configuration-protected.js only for an App Spec with configurationIdentity,
+// so that edge is gated as well. The build command requires managed-create-transport.js only to make (and compose) the managed create
+// gate of an apply where protected configuration is in play (sdk-build.js protectedConfigurationInPlay), and the engine requires the
+// configuration hookup's modules only inside protectedConfigurationFor, which it calls only once that gate exists; those edges are gated
+// too. Apart
// from those gated edges the default build must load none of the new modules, and must still hand the engine the plain pass-through.
-const GATED_EDGES = [['sdk-build.js', 'creates-stable-build.js'], ['sdk-build.js', 'creates-catalog.js'], ['sdk-build.js', 'rule-settlement.js'], ['app-spec.js', 'rule-settlement.js'], ['declared-rule-io.js', 'rule-settlement.js'], ['sdk-build.js', 'bpf-settlement.js'], ['app-spec.js', 'bpf-settlement.js'], ['declared-bpf-io.js', 'bpf-settlement.js'], ['dashboard-reconcile.js', 'creates-identity.js'], ['dashboard-recovery-workspace.js', 'creates-local.js']];
+const GATED_EDGES = [['sdk-build.js', 'creates-stable-build.js'], ['sdk-build.js', 'creates-catalog.js'], ['sdk-build.js', 'rule-settlement.js'], ['app-spec.js', 'rule-settlement.js'], ['declared-rule-io.js', 'rule-settlement.js'], ['sdk-build.js', 'bpf-settlement.js'], ['app-spec.js', 'bpf-settlement.js'], ['declared-bpf-io.js', 'bpf-settlement.js'], ['dashboard-reconcile.js', 'creates-identity.js'], ['dashboard-recovery-workspace.js', 'creates-local.js'], ['verify-model-app.js', 'configuration-protected.js'],
+ ['build-model-app.js', 'managed-create-transport.js'], ['sdk-build.js', 'managed-create-context.js'], ['sdk-build.js', 'configuration-create-bindings.js'], ['sdk-build.js', 'configuration-protected.js']];
const SCRIPTS = path.join(__dirname, '..');
const NEW_MODULES = ['creates-identity.js', 'creates-capabilities.js', 'creates-port.js', 'creates-catalog.js'].map((f) => path.join(SCRIPTS, 'lib', f));
function requireGraph(entry, { gated = false } = {}) {
@@ -288,6 +294,23 @@ test('the default build loads none of the stable-identity modules and still wire
const dashboardScope = fs.readFileSync(path.join(SCRIPTS, 'lib', 'dashboard-recovery-workspace.js'), 'utf8');
assert.match(dashboardScope, /^const createsLocal = \(\) => require\('\.\/creates-local\.js'\);$/m);
assert.equal(dashboardScope.match(/require\('\.\/creates-local\.js'\)/g).length, 1);
+ // Verify loads the protected configuration only behind the opt-in.
+ const verifier = fs.readFileSync(path.join(SCRIPTS, 'verify-model-app.js'), 'utf8');
+ assert.match(verifier, /spec\.configurationIdentity === 'stable-v1'\r?\n\s*\? require\('\.\/lib\/configuration-protected\.js'\)/);
+ assert.equal(verifier.match(/require\('\.\/lib\/configuration-protected\.js'\)/g).length, 1);
+ // The build command makes the managed create gate only for an apply with protected configuration in play, and makeSdk composes it
+ // only when it was given one; the engine loads the hookup's modules only in protectedConfigurationFor, called only with that gate.
+ const command = fs.readFileSync(path.join(SCRIPTS, 'build-model-app.js'), 'utf8');
+ assert.match(command, /const writeGate = managedCreateGate \? require\('\.\/lib\/managed-create-transport\.js'\)\.composeWriteGates\(workflowEffectGate, managedCreateGate\) : workflowEffectGate;/);
+ assert.match(command, /const managedCreateGate = opts\.apply && protectedConfigurationInPlay\(spec, \{ apply: true, env, workspaceDir, appDir: opts\.appDir \}\)\r?\n\s*\? require\('\.\/lib\/managed-create-transport\.js'\)\.createDeferredManagedCreateGate\(\) : null;/);
+ assert.equal(command.match(/require\('\.\/lib\/managed-create-transport\.js'\)/g).length, 2);
+ const hookup = engine.slice(engine.indexOf('function protectedConfigurationFor('), engine.indexOf('// The entry every caller enters by.'));
+ for (const m of ['managed-create-context', 'configuration-create-bindings', 'configuration-protected']) {
+ assert.equal(hookup.match(new RegExp(`require\\('\\./${m}\\.js'\\)`, 'g')).length, 1, `${m}.js is required in the hookup factory`);
+ assert.equal(engine.match(new RegExp(`require\\('\\./${m}\\.js'\\)`, 'g')).length, 1, `${m}.js is required nowhere else in the engine`);
+ }
+ assert.match(engine, /if \(opts\.managedCreateGate && workflowStore && !opts\.protectedConfiguration\) \{/);
+ assert.equal(engine.match(/protectedConfigurationFor\(/g).length, 2, 'defined once, called once behind the gate');
assert.ok(graph.has(path.join(SCRIPTS, 'lib', 'creates-passthrough.js')));
for (const m of NEW_MODULES) assert.ok(!graph.has(m), `${path.basename(m)} is not reachable from a default build`);
const build = fs.readFileSync(path.join(SCRIPTS, 'build-model-app.js'), 'utf8');
diff --git a/plugins/model-apps/scripts/tests/halt-retry-policy.test.js b/plugins/model-apps/scripts/tests/halt-retry-policy.test.js
index 439c5f99d..4c17c3d48 100644
--- a/plugins/model-apps/scripts/tests/halt-retry-policy.test.js
+++ b/plugins/model-apps/scripts/tests/halt-retry-policy.test.js
@@ -133,6 +133,7 @@ const DYNAMIC = [
{ 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/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.
const NOT_HALTS = [{ file: 'build-model-app.js', what: 'the journal record of a halt, written after the retry decision' }];
diff --git a/plugins/model-apps/scripts/tests/helpers/build-command-harness.js b/plugins/model-apps/scripts/tests/helpers/build-command-harness.js
index 39ad83831..de6ae1dc5 100644
--- a/plugins/model-apps/scripts/tests/helpers/build-command-harness.js
+++ b/plugins/model-apps/scripts/tests/helpers/build-command-harness.js
@@ -36,9 +36,10 @@ function appFolder(spec) {
// openJournal(held) called as the journal is opened (the real one is opened after it); it may throw;
// engine(held, opts) the engine (runSdkBuild) — `opts` is what buildModelApp hands it — and what it answers (else a success);
// verify(held) the inline verify (else a pass);
-// writeBaseline(held) called as the baseline is written (the real one is written after it); it may throw.
+// writeBaseline(held) called as the baseline is written (the real one is written after it); it may throw;
+// live the live identity a --changed-only apply reads for the app (else the real read, which asks the environment).
// `calls` lists, in order, which doubles ran.
-function command(folder, { argv = [], auth, language, makeSdk, openJournal, engine, verify, writeBaseline } = {}) {
+function command(folder, { argv = [], auth, language, makeSdk, openJournal, engine, verify, writeBaseline, live } = {}) {
const held = () => fs.existsSync(folder.lock);
const authCli = loadCli(path.join(SCRIPTS, 'lib', 'dataverse-auth.js'));
const printed = { at: null, ok: null, heldThen: null };
@@ -62,6 +63,9 @@ function command(folder, { argv = [], auth, language, makeSdk, openJournal, engi
'./lib/verify-spec.js': { ...require('../../lib/verify-spec.js'), verifySpec: async () => { note('verify'); return verify ? verify(held) : { ok: true, checks: [], missing: [] }; } },
'./lib/deployed-baseline.js': { ...realBaseline, writeBaseline: (...a) => { note('baseline'); if (writeBaseline) writeBaseline(held); return realBaseline.writeBaseline(...a); } },
};
+ if (live) {
+ requires['./lib/changed-only-flow.js'] = { ...require('../../lib/changed-only-flow.js'), resolveLiveIdentity: async () => live };
+ }
if (openJournal) {
const realJournal = require('../../lib/build-journal.js');
requires['./lib/build-journal.js'] = { ...realJournal, openJournal: (...a) => { note('journal'); openJournal(held); return realJournal.openJournal(...a); } };
diff --git a/plugins/model-apps/scripts/tests/helpers/configuration-command-child.js b/plugins/model-apps/scripts/tests/helpers/configuration-command-child.js
new file mode 100644
index 000000000..35bbf8d91
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/configuration-command-child.js
@@ -0,0 +1,53 @@
+'use strict';
+// One OS process of the configuration fresh-process tests (configuration-build-real-bundle.test.js): one run of the build
+// command (helpers/configuration-command.js) with the real maker-SDK bundle, over the maker's app folder on disk. The
+// process is the boundary under test: only the binding store and the files under the app folder carry over from one run
+// to the next, never anything a process held in memory.
+// fork(configuration-command-child.js) with an IPC channel; the parent sends { start: { origin, spec, appDir, argv } }.
+// The service is the strict in-memory org in the parent's process (it outlives every child): each request is sent to the
+// parent as { request: n, req } and answered as { reply: n, answer }. The outcome is sent back as { result } before the
+// channel closes: the pid, the exit code or the thrown error's code and message, the payload, stderr, and the throwaway SDK
+// workspace folders the command made (the durable one under the app folder stays) with whether they are gone again.
+const fs = require('node:fs');
+const path = require('node:path');
+const { runCommand } = require('./configuration-command.js');
+
+const pending = new Map();
+let serial = 0;
+
+process.on('message', async (message) => {
+ if (message.reply) {
+ const resume = pending.get(message.reply);
+ pending.delete(message.reply);
+ resume(message.answer);
+ return;
+ }
+ if (!message.start) return;
+ const { origin, spec, appDir, argv } = message.start;
+ const org = {
+ origin,
+ requests: [],
+ request(req) {
+ this.requests.push(req);
+ const n = ++serial;
+ return new Promise((resolve) => {
+ pending.set(n, resolve);
+ process.send({ request: n, req });
+ });
+ },
+ };
+ const storage = [];
+ const out = await runCommand(spec, { org, appDir, ...(argv ? { argv } : {}), onStorage: (dir) => storage.push(dir) });
+ // The maker's durable workspace lives under the app folder and stays; every other one is the run's throwaway workspace.
+ const throwaway = storage.filter((dir) => !path.resolve(dir).startsWith(path.resolve(appDir) + path.sep));
+ const result = {
+ pid: process.pid,
+ exitCode: out.exitCode,
+ thrown: out.thrown ? { code: out.thrown.code, message: String(out.thrown.message) } : null,
+ payload: out.payload,
+ stderr: out.stderr,
+ workspaceDirs: throwaway,
+ workspacesRemoved: throwaway.every((dir) => !fs.existsSync(dir)),
+ };
+ process.send({ result }, () => process.disconnect());
+});
diff --git a/plugins/model-apps/scripts/tests/helpers/configuration-command.js b/plugins/model-apps/scripts/tests/helpers/configuration-command.js
new file mode 100644
index 000000000..3f70b12ac
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/configuration-command.js
@@ -0,0 +1,79 @@
+'use strict';
+// One run of the build COMMAND (build-model-app.js main) with the SDK it makes itself over the real maker-SDK bundle, for the
+// configuration tests (configuration-build-real-bundle.test.js) and for one OS process of their fresh-process tests
+// (configuration-command-child.js). Only what reaches outside the process is a double: the transport (`org.request`, behind
+// the plugin's own az-token client), the identity checks, the language read, the page backend and telemetry. Each SDK the
+// command makes is watched for `initWorkspace`, which reads and writes local files only.
+//
+// `org` is anything with `origin`, `request(req)` and a `requests` array: the strict in-memory org in the test's process, or a
+// proxy that forwards each request to it from a child process. `appDir` is the maker's app folder; the binding store lives
+// under it, so a second run over the same folder (in this process or another) meets what the first left there.
+const fs = require('node:fs');
+const path = require('node:path');
+const { loadCli } = require('./cli-harness.js');
+
+const SCRIPTS = path.join(__dirname, '..', '..');
+
+// `--allow-destructive` skips the read-only collision check, whose reads (app modules, forms) the strict org does not model.
+// `onStorage(dir)` sees each SDK workspace folder the command makes; `liveIdentity` is the changed-only flow's live identity
+// (an object, or a function returning one), none by default.
+function runCommand(spec, { org, appDir, apply = true, argv = ['--stage', 'data', '--allow-destructive'], liveIdentity, onStorage } = {}) {
+ const realHttp = require('../../lib/sdk-http-client.js');
+ const realMakerSdk = require('../../lib/maker-sdk.js');
+ fs.mkdirSync(appDir, { recursive: true });
+ const specPath = path.join(appDir, 'app-spec.json');
+ fs.writeFileSync(specPath, JSON.stringify(spec));
+ const sdks = [];
+ const authCli = loadCli(path.join(SCRIPTS, 'lib', 'dataverse-auth.js'));
+ const cli = loadCli(path.join(SCRIPTS, 'build-model-app.js'), {
+ argv: ['--env', org.origin, '--spec', `@${specPath}`, ...(apply ? ['--apply'] : []), '--non-interactive', ...argv],
+ env: { PATH: path.dirname(process.execPath), POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1' },
+ requires: {
+ './lib/dataverse-auth.js': { ...authCli.exports, preflightAuth: async () => ({ ok: true }) },
+ // The changed-only flow's live identity (a WhoAmI and an app lookup the org does not model).
+ './lib/changed-only-flow.js': { ...require('../../lib/changed-only-flow.js'), resolveLiveIdentity: async () => (typeof liveIdentity === 'function' ? liveIdentity() : liveIdentity || null) },
+ './lib/entity-provision.js': { ...require('../../lib/entity-provision.js'), resolveAuthoringLanguage: async () => 1033 },
+ './lib/sdk-http-client.js': {
+ ...realHttp,
+ createAzHttpClient: (env, o = {}) => realHttp.createAzHttpClient(env, { ...o, getToken: () => 'test-token-0123456789abcdef', request: (req) => org.request(req), sleep: async () => {} }),
+ },
+ './lib/maker-sdk.js': {
+ ...realMakerSdk,
+ createNodeWorkspaceStorage: (dir) => {
+ if (onStorage) onStorage(dir);
+ return realMakerSdk.createNodeWorkspaceStorage(dir);
+ },
+ createMakerSdk: (o) => {
+ const sdk = realMakerSdk.createMakerSdk(o);
+ const seen = { scoped: !!o.solutionUniqueName, inits: 0, requestsAtInit: [] };
+ const init = sdk.initWorkspace.bind(sdk);
+ sdk.initWorkspace = async () => {
+ seen.inits += 1;
+ const before = org.requests.length;
+ await init();
+ seen.requestsAtInit.push(org.requests.length - before);
+ };
+ sdks.push(seen);
+ return sdk;
+ },
+ },
+ './lib/genpage-sdk.js': { ...require('../../lib/genpage-sdk.js'), makeGenpageSdk: () => ({ dispose: async () => ({ left: [] }) }) },
+ './lib/telemetry/skill-completed.js': { ...require('../../lib/telemetry/skill-completed.js'), emitSkillCompleted: async () => {} },
+ },
+ });
+ return (async () => {
+ let exitCode;
+ let thrown;
+ try {
+ await cli.main();
+ } catch (e) {
+ if (e && e.exitCode !== undefined) exitCode = e.exitCode;
+ else thrown = e;
+ }
+ let payload;
+ try { payload = JSON.parse(authCli.stdoutText()); } catch { payload = undefined; }
+ return { org, appDir, sdks, exitCode, thrown, payload, stderr: [...cli.stderr, ...authCli.stderr].join('') };
+ })();
+}
+
+module.exports = { runCommand };
diff --git a/plugins/model-apps/scripts/tests/helpers/fake-config-org.js b/plugins/model-apps/scripts/tests/helpers/fake-config-org.js
index 35d0c73c8..bd5c11384 100644
--- a/plugins/model-apps/scripts/tests/helpers/fake-config-org.js
+++ b/plugins/model-apps/scripts/tests/helpers/fake-config-org.js
@@ -119,11 +119,18 @@ class Unmodelled extends Error {}
* @param {string} [options.origin]
* @param {Array<{logicalName:string, duplicateDetectionEnabled?:boolean, attributes?:string[]}>} [options.tables]
* @param {{uniqueName:string, version?:string, prefix?:string, managed?:boolean}} [options.solution]
- * @param {(req:{method:string,path:string,body:any}) => ({statusCode:number, body?:any}|undefined)} [options.intercept]
- * answers a request before the store does (used to provoke a refusal or a lost answer)
+ * @param {(req:{method:string,path:string,body:any}) => ({statusCode:number, body?:any}|undefined|Promise<...>)} [options.intercept]
+ * answers a request before the store does (used to provoke a refusal or a lost answer); it may be async, so it can
+ * let the store apply the request first and then lose the answer
* @param {boolean} [options.childrenJoin] a create sent with a solution header puts the children it carries (or a child
* created on its own) into that solution too. Off by default: a compound create's children are then left out, the
* behaviour the platform's own duplicate-rule code works around, so a caller must prove (and add) each child itself.
+ * @param {number} [options.pageSize] server-driven paging: a collection read without `$top` answers at most this many rows
+ * and, when more remain, an absolute `@odata.nextLink` carrying `$skiptoken=<offset>`. Off by default (one page).
+ * @param {boolean} [options.liveRowShape] answer two rows as a live environment does: a connection reference created without
+ * `promptingbehavior` stores the platform's create default 0 (a live read shows `"promptingbehavior": 0` on every
+ * reference the plugin made), and a `duplicaterules` row is answered WITHOUT `@odata.etag` (a live read of a rule carries
+ * none, while every other configuration row does). Off by default, so the tests written before keep their answers.
*/
function createConfigOrg(options = {}) {
const origin = options.origin || 'https://contoso.crm.dynamics.com';
@@ -212,7 +219,7 @@ function createConfigOrg(options = {}) {
const schema = SETS[set];
const select = query.$select ? query.$select.split(',') : null;
if (select) checkColumns(set, select, `${set} $select`);
- const out = { '@odata.etag': etagOf(row) };
+ const out = options.liveRowShape && set === 'duplicaterules' ? {} : { '@odata.etag': etagOf(row) };
for (const [k, v] of Object.entries(row)) {
if (k === 'versionnumber') continue;
if (!select || select.includes(k) || k === schema.pk) out[k] = v;
@@ -265,6 +272,7 @@ function createConfigOrg(options = {}) {
}
if (parentLink) row[parentLink.fk] = parentLink.id;
if (set === 'duplicaterules' && row.statecode === undefined) { row.statecode = 0; row.statuscode = 0; }
+ if (options.liveRowShape && set === 'connectionreferences' && row.promptingbehavior === undefined) row.promptingbehavior = 0;
row.versionnumber = version++;
row.ismanaged = row.ismanaged || false;
sets.get(set).set(id, row);
@@ -322,6 +330,23 @@ function createConfigOrg(options = {}) {
return rows;
}
+ // One page of a collection read (options.pageSize). The continuation is the same query plus `$skiptoken=<offset>`, as
+ // an absolute URL — the shape Dataverse answers:
+ // { "value": [ ... ], "@odata.nextLink": "https://contoso.crm.dynamics.com/api/data/v9.2/customapis?$select=...&$skiptoken=..." }
+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query/page-results
+ function page(set, query) {
+ const { $skiptoken: token, ...rest } = query;
+ const offset = token === undefined ? 0 : Number(token);
+ if (!Number.isInteger(offset) || offset < 0) throw Object.assign(new Error(`a malformed $skiptoken ${token}`), { status: 400 });
+ const rows = list(set, rest);
+ const out = { value: rows.slice(offset, offset + options.pageSize).map((row) => shape(set, row, rest)) };
+ if (offset + options.pageSize < rows.length) {
+ const search = Object.entries({ ...rest, $skiptoken: String(offset + options.pageSize) }).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join('&');
+ out['@odata.nextLink'] = `${origin}/api/data/v9.2/${set}?${search}`;
+ }
+ return out;
+ }
+
// The duplicate-detection publish job: `PublishDuplicateRule` queues an asyncoperation that, once read, has completed and set the
// rule to Published (statecode 1, statuscode 2). Learn: duplicaterule StatusCode — 0/0 Unpublished, 0/1 Publishing, 1/2 Published.
function publishRule(id) {
@@ -441,15 +466,28 @@ function createConfigOrg(options = {}) {
return json(200, out);
}
- async function dispatch(method, where, body, headers) {
+ // The representation a write answers under `Prefer: return=representation`, as Dataverse renders it: its context names
+ // the set and the selected columns, and a created row echoes the lookups its body bound (the service answers the
+ // `_<lookup>_value` of an `@odata.bind` even when only the primary key is selected), e.g.
+ // {"@odata.context":"<api base>/$metadata#customapirequestparameters(customapirequestparameterid)/$entity",
+ // "@odata.etag":"W/\"7\"","customapirequestparameterid":"<id>","_customapiid_value":"<api id>"}
+ function representation(set, row, query, apiBase, created) {
+ const out = { '@odata.context': `${apiBase}/$metadata#${set}${query.$select ? `(${query.$select})` : ''}/$entity`, ...shape(set, row, query) };
+ if (created) for (const [k, v] of Object.entries(row)) if (/^_.+_value$/.test(k) && v !== null && v !== undefined && !(k in out)) out[k] = v;
+ return out;
+ }
+ // The API base a request named: `https://<host>/api/data/v9.x`.
+ const apiBaseOf = (parsed) => `${parsed.origin}${(/^\/api\/data\/v9\.\d/.exec(parsed.pathname) || ['/api/data/v9.0'])[0]}`;
+
+ async function dispatch(method, where, body, headers, apiBase = `${origin}/api/data/v9.0`) {
const qIndex = where.indexOf('?');
const pathPart = qIndex === -1 ? where : where.slice(0, qIndex);
const query = qIndex === -1 ? {} : parseQuery(where.slice(qIndex));
if (options.intercept) {
- const answer = options.intercept({ method, path: where, body, headers });
+ const answer = await options.intercept({ method, path: where, body, headers });
if (answer) return answer.raw ? answer.raw : json(answer.statusCode, answer.body);
}
- if (method === 'POST' && pathPart === '/$batch') return batch(body);
+ if (method === 'POST' && pathPart === '/$batch') return batch(body, apiBase);
let m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)$/.exec(pathPart);
if (m && method === 'GET') return entityDefinition(m[1], query);
m = /^\/duplicaterules\(([^)]+)\)\/Microsoft\.Dynamics\.CRM\.PublishDuplicateRule$/.exec(pathPart);
@@ -469,13 +507,14 @@ function createConfigOrg(options = {}) {
if (!row) return failure(404, '0x80040217', `${set} With Id = ${key} Does Not Exist`);
return json(200, shape(set, row, query));
}
+ if (method === 'GET' && options.pageSize && !query.$top) return json(200, page(set, query));
if (method === 'GET') return json(200, { value: list(set, query).map((row) => shape(set, row, query)) });
if (method === 'POST' && !key) {
const row = insert(set, body || {});
joinSolution(set, row, headerOf(headers, 'MSCRM.SolutionUniqueName'));
const prefer = headerOf(headers, 'Prefer') || '';
const entityId = `${origin}/api/data/v9.2/${set}(${row[SETS[set].pk]})`;
- if (/return=representation/.test(prefer)) return json(201, shape(set, row, query), { 'odata-entityid': entityId, etag: etagOf(row) });
+ if (/return=representation/.test(prefer)) return json(201, representation(set, row, query, apiBase, true), { 'odata-entityid': entityId, etag: etagOf(row) });
return { statusCode: 204, headers: { 'odata-entityid': entityId, 'odata-version': '4.0' }, body: '' };
}
if (method === 'PATCH' && key) {
@@ -483,7 +522,7 @@ function createConfigOrg(options = {}) {
if (refused) return refused;
const row = sets.get(set).get(normGuid(key));
const prefer = headerOf(headers, 'Prefer') || '';
- if (/return=representation/.test(prefer)) return json(200, shape(set, row, query), { etag: etagOf(row) });
+ if (/return=representation/.test(prefer)) return json(200, representation(set, row, query, apiBase, false), { etag: etagOf(row) });
return { statusCode: 204, headers: { 'odata-version': '4.0', etag: etagOf(row) }, body: '' };
}
if (method === 'DELETE' && key) {
@@ -493,9 +532,9 @@ function createConfigOrg(options = {}) {
throw new Unmodelled('the method');
}
- async function guarded(method, where, body, headers) {
+ async function guarded(method, where, body, headers, apiBase) {
try {
- return await dispatch(method, where, body, headers);
+ return await dispatch(method, where, body, headers, apiBase);
} catch (error) {
if (error instanceof Unmodelled) throw error;
if (error && error.status) return failure(error.status, error.code || '0x80040203', error.message);
@@ -506,13 +545,13 @@ function createConfigOrg(options = {}) {
// `$batch`: one change set, applied atomically — on the first failing operation every change of the set is rolled back and only
// that operation's status is answered.
// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/execute-batch-operations-using-web-api#change-sets
- async function batch(text) {
+ async function batch(text, apiBase) {
const operations = parseBatch(String(text));
const saved = new Map([...sets].map(([k, v]) => [k, structuredClone(v)]));
const statuses = [];
for (const op of operations) {
// eslint-disable-next-line no-await-in-loop
- const res = await guarded(op.method, op.path, op.body, op.headers);
+ const res = await guarded(op.method, op.path, op.body, op.headers, op.apiBase || apiBase);
if (res.statusCode < 200 || res.statusCode >= 300) {
for (const [k, v] of saved) sets.set(k, v);
return batchAnswer([{ contentId: op.contentId, status: res.statusCode, body: res.body }]);
@@ -560,7 +599,7 @@ function createConfigOrg(options = {}) {
const payload = headEnd === -1 ? '' : http.slice(headEnd).replace(/^\r?\n\r?\n/, '').replace(/\r?\n$/, '');
const parsed = new URL(url, origin);
const where = decodeURIComponent(parsed.pathname + parsed.search).replace(API_ROOT, '');
- return { contentId: (/^Content-ID:\s*(\S+)/im.exec(mime) || [])[1], method, path: where, headers, body: payload ? JSON.parse(payload) : undefined };
+ return { contentId: (/^Content-ID:\s*(\S+)/im.exec(mime) || [])[1], method, path: where, headers, body: payload ? JSON.parse(payload) : undefined, apiBase: apiBaseOf(parsed) };
});
}
function batchAnswer(parts) {
@@ -579,8 +618,9 @@ function createConfigOrg(options = {}) {
`HTTP/1.1 ${part.status} ${part.status < 300 ? (part.status === 204 ? 'No Content' : 'OK') : 'Bad Request'}`,
...Object.entries(part.headers || {}).filter(([k]) => /^(odata-entityid|location|etag)$/i.test(k)).map(([k, v]) => `${k === 'odata-entityid' ? 'OData-EntityId' : k}: ${v}`),
'OData-Version: 4.0',
+ // The CRLF before the next delimiter belongs to the delimiter (RFC 2046), so a body is one line and no blank
+ // line follows it, as the service answers.
...(part.body ? ['Content-Type: application/json; odata.metadata=minimal', '', String(part.body)] : ['']),
- '',
].join('\r\n')),
`--${inner}--`,
`--${outer}--`,
@@ -603,7 +643,7 @@ function createConfigOrg(options = {}) {
}
requests.push(recorded);
try {
- const answer = await guarded(method, where, parsedBody, headers);
+ const answer = await guarded(method, where, parsedBody, headers, apiBaseOf(parsed));
recorded.status = answer.statusCode;
return answer;
} catch (error) {
diff --git a/plugins/model-apps/scripts/tests/helpers/managed-rows.js b/plugins/model-apps/scripts/tests/helpers/managed-rows.js
new file mode 100644
index 000000000..4384c2a0b
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/managed-rows.js
@@ -0,0 +1,98 @@
+'use strict';
+// Shared fixtures for the configuration row families of the managed binding store (lib/managed-bindings.js
+// `rowProtocol`), its request boundary (lib/managed-create-transport.js) and its lifecycle (lib/managed-create-context.js):
+// one Custom API with one request parameter, every id a fixed GUID, every hash a fixed digit run.
+const { openManagedBindings } = require('../../lib/managed-bindings.js');
+const { environmentFingerprint } = require('../../lib/page-ownership-records.js');
+const { apiPath } = require('../../lib/workflow-effect-context.js');
+
+const ENV = 'https://contoso.crm.dynamics.com';
+const APP = 'contoso_app';
+const SOL = 'contoso_solution';
+const FP = environmentFingerprint(ENV);
+const H = (c) => c.repeat(64);
+const API = '11111111-1111-4111-8111-111111111111';
+const REQ = '22222222-2222-4222-8222-222222222222';
+const FORM = '33333333-3333-4333-8333-333333333333';
+const API_KEY = 'contoso_api';
+const REQ_KEY = JSON.stringify([API_KEY, 'request:p']);
+
+const open = (dir) => openManagedBindings({ workspaceDir: dir, environment: ENV, appUniqueName: APP, solutionUniqueName: SOL });
+const rec = (kind, key, id, over = {}) => ({ formatVersion: 1, appUniqueName: APP, environmentFingerprint: FP, kind, key, id, intentSha256: H('a'), origin: 'created', ...over });
+const PROOF = { savedSha256: H('1'), semanticSha256: H('2'), preservationSha256: H('3'), expectedChildrenSha256: H('4') };
+const codeOf = (fn) => { try { fn(); } catch (e) { return e.code || e.name; } return null; };
+
+const protocolRow = (kind, key, id, parentId) => ({ kind, key, id, parentId, mode: 'create', expectedSha256: H('9'), sensitiveInput: false, sentFields: null, sentSha256: null, dispatched: false });
+
+/** A store prepare plan (prepareAttemptSet) for one Custom API and its request parameter. */
+function apiPlan({ key = API_KEY, api = API, req = REQ, reqKey = JSON.stringify([key, 'request:p']) } = {}) {
+ return {
+ family: 'customApi', key, baseGeneration: null, root: { kind: 'customApi', key, id: api }, declarationSha256: H('e'),
+ rowProtocol: {
+ version: 1, rows: [protocolRow('customApi', key, api, null), protocolRow('customApiRequestParameter', reqKey, req, api)], preserved: [],
+ completion: { ruleState: null, members: [{ kind: 'customApi', id: api, componentType: 10134 }, { kind: 'customApiRequestParameter', id: req, componentType: 10135 }] },
+ effects: [{ kind: 'membership', id: api, dispatched: false }, { kind: 'membership', id: req, dispatched: false }], cohort: null,
+ },
+ };
+}
+
+/** The expected proof (markAttemptSetSending) of apiPlan. */
+function apiExpected({ key = API_KEY, api = API, req = REQ, reqKey = JSON.stringify([key, 'request:p']) } = {}) {
+ return {
+ proofVersion: 1, proofSchema: 'configuration-rows-v1', rootId: api, baseProofSha256: null, sentProjectionSha256: H('b'), preservationSha256: H('c'), baseObservation: null,
+ children: [{ kind: 'customApiRequestParameter', key: reqKey, namespaceParentId: api, id: req, associationSha256: H('d') }],
+ };
+}
+
+/** The consumer state (commitGroupSet) of apiPlan. */
+function apiConsumer({ key = API_KEY, api = API, req = REQ, reqKey = JSON.stringify([key, 'request:p']) } = {}) {
+ return {
+ version: 1, rows: [
+ { kind: 'customApi', key, id: api, parentId: null, projectionSha256: H('5'), sensitiveInput: false },
+ { kind: 'customApiRequestParameter', key: reqKey, id: req, parentId: api, projectionSha256: H('6'), sensitiveInput: false }],
+ };
+}
+
+/** Commit one form group through the version-1 path, so a store holds an old family's group. */
+function settleForm(store) {
+ const scope = { type: 'table', table: 'account' };
+ const token = store.prepareAttempt({ family: 'form', key: 'account/main', baseGeneration: null, root: { kind: 'form', key: 'account/main', id: FORM }, knownScopes: [scope], declarationSha256: H('e'), publication: { scope, state: 'owed' } });
+ store.markSending(token, { proofVersion: 1, proofSchema: 'form-v1', rootId: FORM, baseProofSha256: null, sentProjectionSha256: H('b'), preservationSha256: H('c'), baseObservation: null, children: [] });
+ store.noteSaved(token, { proof: { savedSha256: H('1') }, acknowledgedRoot: true });
+ return store.commitGroup({ token, baseGeneration: null, records: [rec('form', 'account/main', FORM)], proof: PROOF, consumerState: { declaration: { name: 'Main' }, children: {}, proofSchema: 'form-v1' }, publication: { scope, state: 'owed', desiredSha256: H('5'), dispatchToken: null } });
+}
+
+const URL_API = `${ENV}/api/data/v9.2/customapis`;
+const URL_MEMBER = `${ENV}/api/data/v9.2/AddSolutionComponent`;
+
+/** The deep insert of one Custom API and its one request parameter (the parameter names its parent as `parent`). */
+const apiBody = (api = API, req = REQ, parent = api) => ({ uniquename: API_KEY, customapiid: api, CustomAPIRequestParameters: [{ uniquename: 'p', customapirequestparameterid: req, parent }] });
+
+/**
+ * A test driver's classifier for `token`: the Custom API deep insert is the root and its one parameter, an
+ * AddSolutionComponent is a membership effect, and anything else is not the set's (null).
+ */
+function apiClassifier(token) {
+ // Loaded here, not at the top: the store's own tests use these fixtures without the request boundary.
+ const { sentProjection } = require('../../lib/managed-create-transport.js');
+ return ({ method, url, body }) => {
+ const p = apiPath(url);
+ if (method === 'POST' && p === 'customapis') {
+ const b = JSON.parse(body);
+ const c = b.CustomAPIRequestParameters[0];
+ return {
+ type: 'rows', token, expectTable: 'customapis', expectKey: 'customapiid', rows: [
+ { kind: 'customApi', key: b.uniquename, id: b.customapiid, parentId: null, ...sentProjection({ uniquename: b.uniquename, customapiid: b.customapiid }) },
+ {
+ kind: 'customApiRequestParameter', key: JSON.stringify([b.uniquename, `request:${c.uniquename}`]), id: c.customapirequestparameterid, parentId: c.parent, ...sentProjection({ uniquename: c.uniquename }),
+ answer: { at: 'CustomAPIRequestParameters', key: 'customapirequestparameterid', match: { uniquename: c.uniquename } },
+ },
+ ],
+ };
+ }
+ if (method === 'POST' && p === 'AddSolutionComponent') return { type: 'effect', token, kind: 'membership', id: JSON.parse(body).ComponentId };
+ return null;
+ };
+}
+
+module.exports = { ENV, APP, SOL, FP, H, API, REQ, FORM, API_KEY, REQ_KEY, PROOF, URL_API, URL_MEMBER, open, rec, codeOf, apiPlan, apiExpected, apiConsumer, settleForm, apiBody, apiClassifier };
diff --git a/plugins/model-apps/scripts/tests/lint-app-spec.test.js b/plugins/model-apps/scripts/tests/lint-app-spec.test.js
index 08d8d406c..c5b8f242b 100644
--- a/plugins/model-apps/scripts/tests/lint-app-spec.test.js
+++ b/plugins/model-apps/scripts/tests/lint-app-spec.test.js
@@ -210,8 +210,8 @@ test('CLI --strict turns warnings into a failure', () => {
});
// #799: `type` on a view entry was shown by older docs and shipped samples and never had an effect, so a spec carrying it must keep passing
-// --strict; a genuine typo (`filter` for `filters`) drops the filter silently, so --strict failing on it is the point of the warning.
-// The base spec carries other advice (no navigation, personas or pages), so these two start from one that lints clean.
+// --strict; a genuine typo (`filter` for `filters`) drops the filter silently, so it is an error (#827), not advice.
+// The base spec carries other advice (no navigation, personas or pages), so these start from one that lints clean.
const strictClean = (viewExtra) => {
const s = good();
s.views = [{ entity: 'c_order', name: 'Open Orders', columns: ['c_name'], ...viewExtra }];
@@ -231,14 +231,21 @@ test('CLI --strict still passes a view that carries the old `type` key, with no
assert.strictEqual(payload.ok, true);
});
-test('CLI --strict fails on a misspelled view key that the build would drop; without --strict the spec still passes', () => {
+test('CLI refuses a misspelled view key that the build would drop, with or without --strict', () => {
const s = strictClean({ filter: [{ attr: 'c_name', op: 'eq', value: 'x' }] });
- assert.strictEqual(runCli(s).code, 0, 'a warning alone passes without --strict');
- const strict = runCli(s, ['--strict', '--json']);
- assert.strictEqual(strict.code, 1);
- const payload = JSON.parse(strict.stdout);
- assert.strictEqual(payload.ok, false);
- assert.ok(payload.warnings.some((w) => /unknown key 'filter'.*did you mean 'filters'\?/.test(w)), JSON.stringify(payload.warnings));
+ for (const args of [['--json'], ['--strict', '--json']]) {
+ const run = runCli(s, args);
+ assert.strictEqual(run.code, 1, `${args.join(' ')}: ${run.stdout}`);
+ const payload = JSON.parse(run.stdout);
+ assert.strictEqual(payload.ok, false);
+ assert.ok(payload.errors.some((e) => /unknown key 'filter'.*did you mean 'filters'\?/.test(e)), JSON.stringify(payload.errors));
+ assert.deepStrictEqual(payload.warnings, [], 'it is an error only, not also a warning');
+ }
+});
+
+test('CLI still passes a view with filters and sort without --strict or with it', () => {
+ const s = strictClean({ filters: [{ attr: 'c_name', op: 'eq', value: 'x' }], sort: [{ attr: 'c_name', dir: 'asc' }] });
+ for (const args of [[], ['--strict']]) assert.strictEqual(runCli(s, args).code, 0, args.join(' '));
});
test('CLI reports an unreadable spec by name rather than a generic gate error', () => {
diff --git a/plugins/model-apps/scripts/tests/managed-bindings-rows.test.js b/plugins/model-apps/scripts/tests/managed-bindings-rows.test.js
new file mode 100644
index 000000000..c32f2efed
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/managed-bindings-rows.test.js
@@ -0,0 +1,365 @@
+'use strict';
+// The configuration row families of the managed binding store (lib/managed-bindings.js ROW_FAMILIES, `rowProtocol`):
+// a version-2 file that an old-family-only workspace never gets, sets of attempts prepared, sent and committed in one
+// write each, every row sealed once before its request leaves, and ownership proved row by row — a root's
+// acknowledgement or approval never mints a child.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const crypto = require('node:crypto');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { CODES, managedManifestView, readManagedManifest } = require('../lib/managed-bindings.js');
+const { ENV, APP, SOL, FP, H, API, REQ, FORM, API_KEY, REQ_KEY, PROOF, open, rec, codeOf, apiPlan, apiExpected, apiConsumer, settleForm } = require('./helpers/managed-rows.js');
+
+const API2 = '55555555-5555-4555-8555-555555555555';
+const REQ2 = '66666666-6666-4666-8666-666666666666';
+const dirOf = () => makeTempDir('mb-rows-');
+const text = (store) => fs.readFileSync(store.file, 'utf8');
+const SEALED = [
+ { kind: 'customApi', key: API_KEY, id: API, sentFields: ['uniquename', 'customapiid'], sentSha256: H('7') },
+ { kind: 'customApiRequestParameter', key: REQ_KEY, id: REQ, sentFields: ['uniquename'], sentSha256: H('8') },
+];
+const proposal = (token, over = {}) => ({
+ token, baseGeneration: null, records: [rec('customApi', API_KEY, API), rec('customApiRequestParameter', REQ_KEY, REQ, { parentKey: API_KEY })],
+ proof: PROOF, consumerState: apiConsumer(), proofSchema: 'configuration-rows-v1', ...over,
+});
+function sending(store, plans = [apiPlan()], expecteds = [apiExpected()]) {
+ const tokens = store.prepareAttemptSet(plans);
+ return store.markAttemptSetSending(tokens.map((token, i) => ({ token, expected: expecteds[i] })));
+}
+
+test('an old-family store stays version 1; the first configuration prepare writes version 2 and keeps every old group', () => {
+ const dir = dirOf();
+ const store = open(dir);
+ settleForm(store);
+ const before = JSON.parse(text(store));
+ assert.equal(before.schemaVersion, 1);
+ store.prepareAttemptSet([apiPlan()]);
+ const after = JSON.parse(text(store));
+ assert.equal(after.schemaVersion, 2);
+ assert.deepEqual(after.groups, before.groups);
+ assert.equal(open(dir).readGroup('customApi', API_KEY).pending.rowProtocol.rows.length, 2);
+});
+
+test('prepareAttemptSet is one write: a refusal of any plan writes nothing', () => {
+ const dir = dirOf();
+ const store = open(dir);
+ store.prepareAttemptSet([apiPlan()]);
+ const before = text(store);
+ const second = apiPlan({ key: 'contoso_other', api: API2, req: REQ2 });
+ assert.equal(codeOf(() => store.prepareAttemptSet([second, apiPlan()])), CODES.pending);
+ assert.equal(text(store), before);
+ assert.equal(codeOf(() => store.prepareAttemptSet([{ ...second, family: 'form' }])), CODES.notSettled);
+ assert.equal(codeOf(() => store.prepareAttemptSet([second], { cohort: 'c1' })), CODES.notSettled);
+ assert.equal(text(store), before);
+});
+
+test('one physical row is never prepared under two groups', () => {
+ const dir = dirOf();
+ const store = open(dir);
+ store.prepareAttemptSet([apiPlan()]);
+ const before = text(store);
+ assert.throws(() => store.prepareAttemptSet([apiPlan({ key: 'contoso_other', api: API2 })]));
+ assert.equal(text(store), before);
+});
+
+test('each row is sealed once, before it is sent, under the window epoch of the run that claimed it', () => {
+ const store = open(dirOf());
+ const [{ token, epoch }] = sending(store);
+ assert.equal(epoch, 1);
+ assert.equal(codeOf(() => store.sealRowDispatch({ token, epoch: 2, rows: [SEALED[0]] })), CODES.pending, 'an older or newer epoch sends nothing');
+ assert.equal(codeOf(() => store.sealRowDispatch({ token, epoch, rows: [{ ...SEALED[1], id: API2 }] })), CODES.requestMismatch, 'a row under another id');
+ store.sealRowDispatch({ token, epoch, rows: SEALED });
+ assert.equal(codeOf(() => store.sealRowDispatch({ token, epoch, rows: [{ ...SEALED[0], sentFields: ['x'] }] })), CODES.requestMismatch, 'a second send of a sealed row');
+ const row = store.readGroup('customApi', API_KEY).pending.rowProtocol.rows[0];
+ assert.deepEqual([row.dispatched, row.sentFields, row.sentSha256], [true, ['customapiid', 'uniquename'], H('7')], 'the first sealed projection is kept');
+ assert.equal(codeOf(() => store.markAttemptSetSending([{ token, expected: apiExpected() }], { claim: 'continue' })), CODES.pending, 'a dispatched row is never claimed as unsent');
+});
+
+test('a completion effect is marked once; a dispatched effect alone defeats an unsent claim', () => {
+ const store = open(dirOf());
+ const [{ token, epoch }] = sending(store);
+ assert.equal(codeOf(() => store.markRowEffectDispatch({ token, epoch, kind: 'rule-state', id: API })), CODES.requestMismatch);
+ store.markRowEffectDispatch({ token, epoch, kind: 'membership', id: REQ });
+ assert.equal(codeOf(() => store.markRowEffectDispatch({ token, epoch, kind: 'membership', id: REQ })), CODES.requestMismatch);
+ assert.equal(codeOf(() => store.markAttemptSetSending([{ token, expected: apiExpected() }], { claim: 'continue' })), CODES.pending);
+});
+
+test('an attempt that sent nothing is claimed again under a new epoch, which fences the older run', () => {
+ const store = open(dirOf());
+ const [{ token }] = sending(store);
+ const [{ epoch }] = store.markAttemptSetSending([{ token, expected: apiExpected() }], { claim: 'continue' });
+ assert.equal(epoch, 2);
+ assert.equal(codeOf(() => store.sealRowDispatch({ token, epoch: 1, rows: SEALED })), CODES.pending);
+ store.sealRowDispatch({ token, epoch, rows: SEALED });
+});
+
+// The run that holds an attempt releases it after the operation was refused before its first request: only at its own
+// epoch and only while the attempt's own record proves nothing it may have sent can land. Anything else keeps it.
+test('retireProvenUnsentAttempt releases only a sending attempt that sent nothing, at the epoch of the run that holds it', () => {
+ const sendingObserved = (store) => {
+ const [token] = store.prepareAttemptSet([apiPlan()]);
+ return store.markAttemptSetSending([{ token, expected: apiExpected() }], { claim: 'first', observed: true })[0];
+ };
+ const kept = [
+ ['a counted send', (store, { token, epoch }) => store.noteAttemptDispatch(token, epoch)],
+ ['a sealed row', (store, { token, epoch }) => store.sealRowDispatch({ token, epoch, rows: [SEALED[0]] })],
+ ['a dispatched effect', (store, { token, epoch }) => store.markRowEffectDispatch({ token, epoch, kind: 'membership', id: REQ })],
+ ['a claim by a later run', (store, { token }) => store.markAttemptSetSending([{ token, expected: apiExpected() }], { claim: 'continue', observed: true })],
+ ];
+ for (const [what, move] of kept) {
+ const store = open(dirOf());
+ const held = sendingObserved(store);
+ move(store, held);
+ const before = text(store);
+ assert.equal(codeOf(() => store.retireProvenUnsentAttempt(held)), CODES.pending, what);
+ assert.equal(text(store), before, `${what}: nothing is written`);
+ assert.ok(store.readGroup('customApi', API_KEY).pending, `${what}: the attempt stays for recovery`);
+ }
+ const prepared = open(dirOf());
+ const [token] = prepared.prepareAttemptSet([apiPlan()]);
+ assert.equal(codeOf(() => prepared.retireProvenUnsentAttempt({ token, epoch: 1 })), CODES.pending, 'a prepared attempt has no send window to prove anything');
+ assert.equal(codeOf(() => prepared.retireProvenUnsentAttempt({ token })), CODES.notSettled, 'the epoch is required');
+
+ const store = open(dirOf());
+ const held = sendingObserved(store);
+ assert.deepEqual(store.retireProvenUnsentAttempt(held), { retired: true, effects: 0 });
+ const group = store.readGroup('customApi', API_KEY);
+ assert.ok(!group.pending, 'the attempt is gone');
+ assert.throws(() => store.sealRowDispatch({ token: held.token, epoch: held.epoch, rows: [SEALED[0]] }), 'the released run sends nothing more under it');
+});
+
+test('ownership is proved row by row: a root acknowledgement never mints a child, and a child adoption names it exactly', () => {
+ const dir = dirOf();
+ const store = open(dir);
+ const [{ token, epoch }] = sending(store);
+ store.sealRowDispatch({ token, epoch, rows: SEALED });
+ store.noteSaved(token, { proof: null, acknowledgedRoot: true });
+ assert.equal(codeOf(() => store.commitGroupSet([proposal(token)])), CODES.completion, 'a created child needs its own receipt');
+ const adopted = proposal(token, { records: [rec('customApi', API_KEY, API), rec('customApiRequestParameter', REQ_KEY, REQ, { parentKey: API_KEY, origin: 'adopted' })] });
+ assert.equal(codeOf(() => store.commitGroupSet([adopted])), CODES.adoptionRequired, 'an adopted child needs its own approval');
+ assert.equal(codeOf(() => store.commitGroupSet([{ ...adopted, adoptionApproved: true }])), CODES.adoptionRequired, 'the root approval is not the child\'s');
+ assert.equal(codeOf(() => store.commitGroupSet([{ ...adopted, adoptionApprovedChildren: [{ kind: 'customApiRequestParameter', key: JSON.stringify([API_KEY, 'request:q']), id: REQ }] }])), CODES.adoptionRequired, 'another slot is another row');
+ const [g] = store.commitGroupSet([{ ...adopted, adoptionApprovedChildren: [{ kind: 'customApiRequestParameter', key: REQ_KEY, id: REQ }] }]);
+ assert.deepEqual(g.records.map((r) => r.origin), ['created', 'adopted']);
+ assert.equal(open(dir).readGroup('customApi', API_KEY).committed.generation, g.generation);
+});
+
+test('a child receipt lets the child be recorded created; an unacknowledged root needs the root approval', () => {
+ const store = open(dirOf());
+ const [{ token, epoch }] = sending(store);
+ store.sealRowDispatch({ token, epoch, rows: SEALED });
+ store.noteSaved(token, { proof: null, acknowledgedChildCreates: [{ kind: 'customApiRequestParameter', key: REQ_KEY, id: REQ }] });
+ assert.equal(codeOf(() => store.commitGroupSet([proposal(token)])), CODES.adoptionRequired);
+ const rootAdopted = proposal(token, { records: [rec('customApi', API_KEY, API, { origin: 'adopted' }), rec('customApiRequestParameter', REQ_KEY, REQ, { parentKey: API_KEY })] });
+ const [g] = store.commitGroupSet([{ ...rootAdopted, adoptionApproved: true }]);
+ assert.deepEqual(g.records.map((r) => r.origin), ['adopted', 'created']);
+});
+
+test('commitGroupSet is one write: a refusal of any proposal commits nothing', () => {
+ const dir = dirOf();
+ const store = open(dir);
+ const two = [apiPlan(), apiPlan({ key: 'contoso_other', api: API2, req: REQ2 })];
+ const [a, b] = sending(store, two, [apiExpected(), apiExpected({ key: 'contoso_other', api: API2, req: REQ2 })]);
+ store.noteSaved(a.token, { proof: null, acknowledgedRoot: true, acknowledgedChildCreates: [{ kind: 'customApiRequestParameter', key: REQ_KEY, id: REQ }] });
+ const before = text(store);
+ const otherKey = JSON.stringify(['contoso_other', 'request:p']);
+ const bProposal = proposal(b.token, { records: [rec('customApi', 'contoso_other', API2), rec('customApiRequestParameter', otherKey, REQ2, { parentKey: 'contoso_other' })], consumerState: apiConsumer({ key: 'contoso_other', api: API2, req: REQ2 }) });
+ assert.equal(codeOf(() => store.commitGroupSet([proposal(a.token), bProposal])), CODES.adoptionRequired);
+ assert.equal(text(store), before, 'the first group is not committed without the second');
+ assert.equal(codeOf(() => store.commitGroupSet([proposal(a.token), proposal(a.token)])), CODES.notSettled);
+});
+
+test('a version-2 file with an unknown family, or a configuration unit in a version-1 file, is unreadable whole', () => {
+ for (const corrupt of [(d) => { d.attempts[0].family = 'command'; }, (d) => { d.schemaVersion = 1; }]) {
+ const dir = dirOf();
+ const store = open(dir);
+ store.prepareAttemptSet([apiPlan()]);
+ const data = JSON.parse(text(store));
+ corrupt(data);
+ fs.writeFileSync(store.file, JSON.stringify(data));
+ assert.equal(codeOf(() => open(dir).snapshot()), CODES.unreadable);
+ }
+});
+
+test('the manifest view lists a committed configuration group with its rows, and a pending one apart', () => {
+ const dir = dirOf();
+ const store = open(dir);
+ const [{ token }] = sending(store);
+ store.noteSaved(token, { proof: null, acknowledgedRoot: true, acknowledgedChildCreates: [{ kind: 'customApiRequestParameter', key: REQ_KEY, id: REQ }] });
+ store.commitGroupSet([proposal(token)]);
+ store.prepareAttemptSet([apiPlan({ key: 'contoso_other', api: API2, req: REQ2 })]);
+ const view = managedManifestView(open(dir).snapshot());
+ assert.deepEqual(view.groups.map((g) => [g.family, g.key, g.rows]), [['customApi', API_KEY, apiConsumer().rows]]);
+ assert.equal(view.groups[0].declaration, undefined);
+ assert.deepEqual(view.pending, [{ family: 'customApi', key: 'contoso_other', code: CODES.pending }]);
+ const read = readManagedManifest({ workspaceDir: dir, environment: ENV, appUniqueName: APP, solutionUniqueName: SOL });
+ assert.deepEqual(read.groups, view.groups);
+});
+
+// --- Versions and vocabulary a newer plugin may write, and the files an older one wrote.
+
+const FORM2 = '44444444-4444-4444-8444-444444444444';
+const DASH = '77777777-7777-4777-8777-777777777777';
+const formScope = (table) => ({ type: 'table', table });
+const prepareForm = (store, key, id, table) => store.prepareAttempt({ family: 'form', key, baseGeneration: null, root: { kind: 'form', key, id }, knownScopes: [formScope(table)], declarationSha256: H('e'), publication: { scope: formScope(table), state: 'owed' } });
+// A version-2 store with a committed Custom API group (groups[0]) and a second one sending (attempts[0]).
+function rowStore() {
+ const dir = dirOf();
+ const store = open(dir);
+ const [{ token }] = sending(store);
+ store.noteSaved(token, { proof: null, acknowledgedRoot: true, acknowledgedChildCreates: [{ kind: 'customApiRequestParameter', key: REQ_KEY, id: REQ }] });
+ store.commitGroupSet([proposal(token)]);
+ sending(store, [apiPlan({ key: 'contoso_other', api: API2, req: REQ2 })], [apiExpected({ key: 'contoso_other', api: API2, req: REQ2 })]);
+ return { dir, store };
+}
+const rewrite = (store, corrupt) => {
+ const data = JSON.parse(text(store));
+ corrupt(data);
+ fs.writeFileSync(store.file, `${JSON.stringify(data, null, 2)}\n`);
+};
+
+test('a row protocol, consumer, record or proof version, a proof schema or a field this build does not know, at any depth of a closed shape, makes the whole store unreadable, and no sibling is written', () => {
+ const newer = {
+ 'row protocol version': (d) => { d.attempts[0].rowProtocol.version = 2; },
+ 'row field': (d) => { d.attempts[0].rowProtocol.rows[1].ordinal = 1; },
+ 'row protocol field': (d) => { d.attempts[0].rowProtocol.order = []; },
+ 'effect field': (d) => { d.attempts[0].rowProtocol.effects[0].after = 'x'; },
+ 'completion field': (d) => { d.attempts[0].rowProtocol.completion.compound = []; },
+ 'member field': (d) => { d.attempts[0].rowProtocol.completion.members[0].behavior = 1; },
+ 'attempt field': (d) => { d.attempts[0].cohortToken = 'c'; },
+ 'expected proof version': (d) => { d.attempts[0].expected.proofVersion = 2; },
+ 'expected proof schema': (d) => { d.attempts[0].expected.proofSchema = 'configuration-rows-v2'; },
+ 'expected field': (d) => { d.attempts[0].expected.batch = null; },
+ 'expected child field': (d) => { d.attempts[0].expected.children[0].order = 0; },
+ 'consumer version': (d) => { d.groups[0].consumerState.version = 2; },
+ 'consumer row field': (d) => { d.groups[0].consumerState.rows[0].privateSha256 = H('1'); },
+ 'consumer field': (d) => { d.groups[0].consumerState.cohort = null; },
+ 'record format': (d) => { d.groups[0].records[1].formatVersion = 2; },
+ 'record field': (d) => { d.groups[0].records[0].cohort = 'c'; },
+ 'group proof schema': (d) => { d.groups[0].proofSchema = 'configuration-rows-v2'; },
+ 'group field': (d) => { d.groups[0].cohort = null; },
+ 'group proof field': (d) => { d.groups[0].proof.cohortSha256 = H('2'); },
+ 'group root field': (d) => { d.groups[0].root.cohort = 'c'; },
+ 'group publication field': (d) => { d.groups[0].publication = { scope: { type: 'table', table: 'account' }, state: 'not-needed', desiredSha256: null, dispatchToken: null, cohort: null }; },
+ 'attempt root field': (d) => { d.attempts[0].root.cohort = 'c'; },
+ 'send window field': (d) => { d.attempts[0].sendWindow = { possible: 0, notStarted: 0, epoch: 1, lane: 0 }; },
+ 'completion reserve field': (d) => { d.attempts[0].completionReserve.spare = 0; },
+ 'known scope field': (d) => { d.attempts[0].knownScopes = [{ type: 'table', table: 'account', lane: 0 }]; },
+ };
+ const outcome = (name, corrupt) => {
+ const { dir, store } = rowStore();
+ rewrite(store, corrupt);
+ const bytes = text(store);
+ return [name, codeOf(() => open(dir)), codeOf(() => store.refresh()), codeOf(() => prepareForm(store, 'account/main', FORM, 'account')), text(store) === bytes];
+ };
+ const got = Object.entries(newer).map(([name, corrupt]) => outcome(name, corrupt));
+ assert.deepEqual(got, Object.keys(newer).map((name) => [name, CODES.unreadable, CODES.unreadable, CODES.unreadable, true]), 'open, refresh and a form write are each refused, and the file is kept as it was');
+});
+
+test('a configuration unit that is merely malformed is isolated, and a sibling is still written', () => {
+ const malformed = {
+ 'a version of the wrong type': (d) => { d.attempts[0].rowProtocol.version = '1'; },
+ 'a missing field': (d) => { delete d.attempts[0].rowProtocol.rows[1].sentSha256; },
+ 'a hash that is not one': (d) => { d.attempts[0].expected.sentProjectionSha256 = 'x'; },
+ 'a root with no id': (d) => { delete d.attempts[0].root.id; },
+ 'a send window count of the wrong type': (d) => { d.attempts[0].sendWindow = { possible: '0', notStarted: 0, epoch: 1 }; },
+ 'a reservation with no used count': (d) => { delete d.attempts[0].completionReserve.used; },
+ // A scope type is untrusted: one that is not a string is malformed, never a property key to look up, and an object
+ // that cannot even be turned into one must not escape the unit as a raw TypeError.
+ 'a scope type that is an object no key can be made of': (d) => { d.attempts[0].knownScopes = [{ type: { toString: null } }]; },
+ 'a scope with no type': (d) => { d.attempts[0].knownScopes = [{ table: 'account' }]; },
+ 'a scope type that is a number': (d) => { d.attempts[0].knownScopes = [{ type: 1, table: 'account' }]; },
+ 'a scope type that is a plain object': (d) => { d.attempts[0].knownScopes = [{ type: {}, table: 'account' }]; },
+ 'a publication scope type no key can be made of': (d) => { d.attempts[0].publication = { scope: { type: { toString: null } }, state: 'owed' }; },
+ };
+ for (const [name, corrupt] of Object.entries(malformed)) {
+ const { dir, store } = rowStore();
+ rewrite(store, corrupt);
+ assert.equal(codeOf(() => store.refresh()), null, `${name}: a refresh reads the rest of the store`);
+ const again = open(dir);
+ assert.equal(codeOf(() => again.readGroup('customApi', 'contoso_other')), CODES.groupInvalid, name);
+ assert.equal(typeof prepareForm(again, 'account/main', FORM, 'account'), 'string', `${name}: a form is still written`);
+ }
+});
+
+test('a set mutation charges every attempt it spends for, and never an attempt it does not name', () => {
+ const store = open(dirOf());
+ const [unrelated] = store.prepareAttemptSet([apiPlan({ key: 'contoso_third', api: '88888888-8888-4888-8888-888888888888', req: '99999999-9999-4999-8999-999999999999' })]);
+ const plans = [apiPlan(), apiPlan({ key: 'contoso_other', api: API2, req: REQ2 })];
+ const tokens = store.prepareAttemptSet(plans);
+ const reserve = (token) => JSON.parse(text(store)).attempts.find((a) => a.token === token).completionReserve;
+ const before = Buffer.byteLength(text(store), 'utf8');
+ store.markAttemptSetSending([{ token: tokens[0], expected: apiExpected() }, { token: tokens[1], expected: apiExpected({ key: 'contoso_other', api: API2, req: REQ2 }) }]);
+ const grown = Buffer.byteLength(text(store), 'utf8') - before;
+ const [a, b] = tokens.map(reserve);
+ assert.ok(a.used > 0 && b.used > 0, `both participants pay (${a.used}, ${b.used})`);
+ assert.ok(a.used + b.used >= grown, `together they pay the whole growth (${a.used} + ${b.used} of ${grown})`);
+ assert.equal(reserve(unrelated).used, 0, 'an attempt the write did not name keeps its whole reservation');
+});
+
+test('an old-family file stays version 1, a dashboard create receipt included; a version-2 file stays 2', () => {
+ const dir = dirOf();
+ const store = open(dir);
+ settleForm(store);
+ const dscope = { type: 'dashboard', id: DASH };
+ const token = store.prepareAttempt({ family: 'dashboard', key: 'ops', baseGeneration: null, root: { kind: 'dashboard', key: 'ops', id: DASH }, knownScopes: [dscope], declarationSha256: H('e'), publication: { scope: dscope, state: 'owed' } });
+ const exp = { proofVersion: 1, proofSchema: 'dashboard-v1', rootId: DASH, baseProofSha256: null, sentProjectionSha256: H('b'), preservationSha256: H('c'), baseObservation: null, children: [] };
+ const { epoch } = store.markSending(token, exp, { observed: true });
+ store.noteDashboardCreateDraft(token, { sendEpoch: epoch, rootId: DASH, draftSha256: H('7'), bodySha256: H('8') });
+ assert.equal(JSON.parse(text(store)).schemaVersion, 1);
+ prepareForm(store, 'contact/main', FORM2, 'contact');
+ assert.equal(JSON.parse(text(store)).schemaVersion, 1, 'dashboard recovery fields alone never upgrade the file');
+ const dir2 = dirOf();
+ settleForm(open(dir2));
+ rewrite(open(dir2), (d) => { d.schemaVersion = 2; });
+ const two = open(dir2);
+ prepareForm(two, 'contact/main', FORM2, 'contact');
+ assert.equal(JSON.parse(text(two)).schemaVersion, 2, 'a version-2 file is never written back as 1');
+});
+
+// The same old-family writes, in the same order and with the same tokens, leave the same bytes on disk as the 2.22.0
+// store wrote (the digests below were taken by running this sequence against that release). A configuration family
+// changes nothing of how a file without one is written: not its version, its fields, their order or its accounting.
+test('old-family writes are byte for byte what the previous release wrote', () => {
+ const WANT = [
+ '7626f752adc2604fe6d56d8255e2482bfcd8893802204045c8012ea2e493667f', '0d3a59184d0b4ff7d6191f82563307354b0a6d047143afa5a914910c6762a4b8',
+ '89e72530691a79dd64ccfd586efec2d1e526d4eadb286c62344d8b9ec9df99ea', '7b499bec0f386f2f781846f475908d9cf94d1aaaff3999fb96494a2667e69abf',
+ '29f17427b57f5560828df60fab078670e297302898634f9c4cdebd77b96c2403', 'a990343e2dd2a8905bf99809660cce51002400b48fb58e69fd4a1c6fe4bd0dfd',
+ 'd01c5c703e36f5f153267f8bde560854fe2747425a7720ecb3fd7bfa84ce652d', 'c7671610f743b8c4346e577579e995f926af7af61b8511fe3e211ed2d2fd0f29',
+ '87dc1d3661ee3e3e88c5b4d3a9f7f72d30b0b9900a2f527e5c14cf195636776f', 'a7e20721e6734d661408cd8aca94f1c90e0741c3fd250dd8f6a3d51b2bf2875c',
+ '43c104fa5531bb0d9ed30619cad14a063a02b1d9b61db8e8e172d32ae61a4bc0', '79faad00eb88d15e84421e44ad96c856c25085eab9f3bd18df07eec634d7e9a8',
+ '2c68665b8246990399cf0c409b2ae7a5be522445dab29287d7fd9eadd3bd5739', 'f36f18b421fb63c989c2876e23f590dfd73afcea9c17c67d9763a1aad117f8ff',
+ ];
+ const real = crypto.randomUUID;
+ let n = 0;
+ crypto.randomUUID = () => `00000000-0000-4000-8000-${String(++n).padStart(12, '0')}`;
+ try {
+ const store = open(dirOf());
+ const got = [];
+ const step = (fn) => { fn(); got.push(crypto.createHash('sha256').update(fs.readFileSync(store.file)).digest('hex')); };
+ const scope = formScope('account');
+ const dscope = { type: 'dashboard', id: DASH };
+ const exp = (rootId, schema) => ({ proofVersion: 1, proofSchema: schema, rootId, baseProofSha256: null, sentProjectionSha256: H('b'), preservationSha256: H('c'), baseObservation: null, children: [] });
+ const record = (kind, key, id) => ({ formatVersion: 1, appUniqueName: APP, environmentFingerprint: FP, kind, key, id, intentSha256: H('a'), origin: 'created' });
+ let t1; let t2; let t3; let epoch; let dispatchToken;
+ step(() => { t1 = prepareForm(store, 'account/main', FORM, 'account'); });
+ step(() => store.markSending(t1, exp(FORM, 'form-v1')));
+ step(() => store.noteSaved(t1, { proof: { savedSha256: H('1') }, acknowledgedRoot: true }));
+ step(() => store.commitGroup({ token: t1, baseGeneration: null, records: [record('form', 'account/main', FORM)], proof: PROOF, consumerState: { declaration: { name: 'Main' }, children: {}, proofSchema: 'form-v1' }, publication: { scope, state: 'owed', desiredSha256: H('5'), dispatchToken: null } }));
+ step(() => { t2 = store.prepareAttempt({ family: 'dashboard', key: 'ops', baseGeneration: null, root: { kind: 'dashboard', key: 'ops', id: DASH }, knownScopes: [dscope], declarationSha256: H('e'), publication: { scope: dscope, state: 'owed' } }); });
+ step(() => { ({ epoch } = store.markSending(t2, exp(DASH, 'dashboard-v1'), { observed: true })); });
+ step(() => store.noteDashboardCreateDraft(t2, { sendEpoch: epoch, rootId: DASH, draftSha256: H('7'), bodySha256: H('8') }));
+ step(() => { ({ dispatchToken } = store.noteDashboardCreateDispatch(t2, { sendEpoch: epoch, bodySha256: H('8') })); });
+ step(() => store.noteAttemptDispatch(t2, epoch));
+ step(() => store.noteDashboardCreateAnswer(t2, { sendEpoch: epoch, dispatchToken, bodySha256: H('8') }));
+ step(() => store.noteSaved(t2, { proof: null, acknowledgedRoot: true }));
+ step(() => store.commitGroup({ token: t2, baseGeneration: null, records: [record('dashboard', 'ops', DASH)], proof: PROOF, consumerState: { declaration: {}, tiles: {}, seedIds: [] }, publication: { scope: dscope, state: 'owed', desiredSha256: H('5'), dispatchToken: null } }));
+ step(() => { t3 = prepareForm(store, 'contact/main', FORM2, 'contact'); });
+ step(() => store.retireUnsentAttempt({ token: t3, baseGeneration: null }));
+ assert.deepEqual(got, WANT);
+ assert.equal(JSON.parse(text(store)).schemaVersion, 1);
+ } finally {
+ crypto.randomUUID = real;
+ }
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/managed-create-batch.test.js b/plugins/model-apps/scripts/tests/managed-create-batch.test.js
new file mode 100644
index 000000000..2d1262478
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/managed-create-batch.test.js
@@ -0,0 +1,491 @@
+'use strict';
+// The one `$batch` a protected create set may send (lib/managed-create-batch.js, admitted by the gate in
+// lib/managed-create-transport.js when the set opts in with `batch`): the Custom API change set the SDK writes to edit an
+// API the set already binds and add new children. Driven through the plugin's real HTTP client with a fake transport,
+// the real binding store and a synthetic driver classifier. The shapes are those the SDK writes and the service answers
+// (live captures, every id and host replaced by a placeholder).
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { createAzHttpClient } = require('../lib/sdk-http-client.js');
+const { apiPath } = require('../lib/workflow-effect-context.js');
+const { MISMATCH, createDeferredManagedCreateGate, runWithManagedCreateSet, sentProjection } = require('../lib/managed-create-transport.js');
+const { batchConfig, parseCustomApiChangeset, readChangesetAnswer } = require('../lib/managed-create-batch.js');
+const { createManagedCreateContext } = require('../lib/managed-create-context.js');
+const { ENV, SOL, H, API, REQ, API_KEY, REQ_KEY, URL_API, URL_MEMBER, open, apiBody, apiClassifier } = require('./helpers/managed-rows.js');
+
+const API9 = `${ENV}/api/data/v9.0`;
+const BATCH_URL = `${API9}/$batch`;
+const NEW_REQ = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const NEW_RESP = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+const OTHER = '77777777-7777-4777-8777-777777777777';
+const NEW_REQ_KEY = JSON.stringify([API_KEY, 'request:Extra']);
+const NEW_RESP_KEY = JSON.stringify([API_KEY, 'response:Out']);
+const BATCH_ID = 'batch_0a0a0a0a-0000-4000-8000-000000000001';
+const CS_ID = 'changeset_0a0a0a0a-0000-4000-8000-000000000002';
+const RB_ID = 'batchresponse_0a0a0a0a-0000-4000-8000-000000000003';
+const RC_ID = 'changesetresponse_0a0a0a0a-0000-4000-8000-000000000004';
+const HELD = 'W/"14860046"';
+const SAVED = 'W/"14863812"';
+const NOT_FOUND = 'configuration-row-not-found';
+
+// --- the request, as cds-maker-sdk renderChangeSet writes it ------------------------------------------------------------
+
+const rootBody = (over = {}) => ({ isprivate: true, ...over });
+const reqBody = (over = {}) => ({
+ customapirequestparameterid: NEW_REQ, uniquename: 'Extra', name: 'contoso_api.Extra', displayname: 'Extra', description: 'Extra', type: 10,
+ logicalentityname: null, isoptional: false, '[email protected]': `/customapis(${API})`, ...over,
+});
+const respBody = (over = {}) => ({
+ customapiresponsepropertyid: NEW_RESP, uniquename: 'Out', name: 'contoso_api.Out', displayname: 'Out', description: 'Out', type: 10,
+ logicalentityname: null, '[email protected]': `/customapis(${API})`, ...over,
+});
+const rootOp = (body = rootBody(), over = {}) => ({ method: 'PATCH', path: `customapis(${API})?$select=customapiid`, body, etag: HELD, ...over });
+const reqOp = (body = reqBody(), over = {}) => ({ method: 'POST', path: 'customapirequestparameters?$select=customapirequestparameterid', body, ...over });
+const respOp = (body = respBody(), over = {}) => ({ method: 'POST', path: 'customapiresponseproperties?$select=customapiresponsepropertyid', body, ...over });
+
+/** A change set of `ops` in the SDK's framing; each op may replace its MIME or HTTP header lines and its body text. */
+function changeset(ops, { eol = '\r\n', boundary = `Content-Type: multipart/mixed;boundary=${CS_ID}` } = {}) {
+ const parts = ops.map((op, i) => [
+ `--${CS_ID}`, ...(op.mime || ['Content-Type: application/http', 'Content-Transfer-Encoding: binary', `Content-ID: ${op.contentId || i + 1}`]), '',
+ `${op.method} ${op.base || API9}/${op.path} HTTP/1.1`,
+ ...(op.headers || ['Content-Type: application/json;type=entry', `MSCRM.SolutionUniqueName: ${SOL}`, ...(op.etag ? [`If-Match: ${op.etag}`] : []), 'Prefer: return=representation']),
+ '', op.text !== undefined ? op.text : JSON.stringify(op.body),
+ ].join(eol));
+ return [`--${BATCH_ID}`, boundary, '', ...parts, `--${CS_ID}--`, `--${BATCH_ID}--`, ''].join(eol);
+}
+
+// --- the answer, as the service sends it --------------------------------------------------------------------------------
+
+const PART_HEADERS = ['Preference-Applied: return=representation', 'Cache-Control: no-store', 'Content-Type: application/json; odata.metadata=minimal', 'OData-Version: 4.0'];
+const rootPart = (id = 1, over = {}, headers = [`ETag: ${SAVED}`, ...PART_HEADERS]) => ({
+ id, status: 'HTTP/1.1 200 OK', headers,
+ body: { '@odata.context': `${API9}/$metadata#customapis(customapiid)/$entity`, '@odata.etag': SAVED, customapiid: API, ...over },
+});
+const reqPart = (id = 2, over = {}, headers = PART_HEADERS) => ({
+ id, status: 'HTTP/1.1 201 Created', headers,
+ body: { '@odata.context': `${API9}/$metadata#customapirequestparameters(customapirequestparameterid)/$entity`, '@odata.etag': 'W/"14863815"', customapirequestparameterid: NEW_REQ, _customapiid_value: API, ...over },
+});
+const respPart = (id = 3, over = {}, headers = PART_HEADERS) => ({
+ id, status: 'HTTP/1.1 201 Created', headers,
+ body: { '@odata.context': `${API9}/$metadata#customapiresponseproperties(customapiresponsepropertyid)/$entity`, '@odata.etag': 'W/"14863816"', customapiresponsepropertyid: NEW_RESP, _customapiid_value: API, ...over },
+});
+// The captured atomic failure: the outer status, and only the failed part, with its OData error envelope.
+const failedPart = (id = 2) => ({
+ id, status: 'HTTP/1.1 412 Precondition Failed', headers: ['Content-Type: application/json; odata.metadata=minimal', 'OData-Version: 4.0'],
+ body: { error: { code: '0x80040333', message: 'A record was not created or updated because a duplicate of the current record already exists.' } },
+});
+function answerText(parts, { eol = '\r\n', boundary = `Content-Type: multipart/mixed; boundary=${RC_ID}` } = {}) {
+ return [`--${RB_ID}`, boundary, '', ...parts.map((p) => [
+ `--${RC_ID}`, 'Content-Type: application/http', 'Content-Transfer-Encoding: binary', `Content-ID: ${p.id}`, '',
+ p.status, ...p.headers, '', p.text !== undefined ? p.text : JSON.stringify(p.body),
+ ].join(eol)), `--${RC_ID}--`, `--${RB_ID}--`, ''].join(eol);
+}
+const answer = (statusCode, parts, opts) => ({ statusCode, headers: { 'content-type': `multipart/mixed; boundary=${RB_ID}` }, body: answerText(parts, opts) });
+
+// --- a store binding the API, and an edit of it that adds two new children ----------------------------------------------
+
+const rowsOf = (mode, extra = []) => [
+ { kind: 'customApi', key: API_KEY, id: API, parentId: null, mode, expectedSha256: H('7') },
+ { kind: 'customApiRequestParameter', key: REQ_KEY, id: REQ, parentId: API, mode, expectedSha256: H('8') },
+ ...extra,
+];
+const planOf = (rows, baseGeneration = null) => ({
+ family: 'customApi', key: API_KEY, baseGeneration, declarationSha256: H('e'), rows,
+ ...(baseGeneration !== null ? { baseObservation: { rowVersion: '14860046', savedSha256: H('1') } } : {}),
+ members: rows.map((r) => ({ kind: r.kind, id: r.id, componentType: r.kind === 'customApi' ? 10134 : r.kind === 'customApiRequestParameter' ? 10135 : 10136 })),
+ effects: rows.filter((r) => r.mode === 'create').map((r) => ({ kind: 'membership', id: r.id })),
+});
+const readOf = (rows) => ({
+ rows: rows.map((r) => ({ kind: r.kind, key: r.key, id: r.id, state: 'present', parentId: r.parentId, projectionSha256: r.expectedSha256 })),
+ members: rows.map((r) => ({ id: r.id, state: 'present' })),
+ ruleState: null,
+});
+const NEW_ROWS = [
+ { kind: 'customApiRequestParameter', key: NEW_REQ_KEY, id: NEW_REQ, parentId: API, mode: 'create', expectedSha256: H('a') },
+ { kind: 'customApiResponseProperty', key: NEW_RESP_KEY, id: NEW_RESP, parentId: API, mode: 'create', expectedSha256: H('b') },
+];
+
+// Create and commit the API and its parameter (one deep insert), then begin the edit: the API and its parameter bound
+// (updates), the two new children to create.
+async function boundEdit(dir) {
+ const firstStore = open(dir);
+ const first = createManagedCreateContext({ store: firstStore, approvals: [], notFoundCode: NOT_FOUND });
+ const created = first.begin([planOf(rowsOf('create'))]);
+ const gate = createDeferredManagedCreateGate();
+ gate.bind(firstStore);
+ await first.run({ attempts: created, classify: apiClassifier(created[0].token), acceptResult: () => true }, async () => {
+ for (const req of [{ url: URL_API, body: apiBody() }, { url: URL_MEMBER, body: { ComponentId: API } }, { url: URL_MEMBER, body: { ComponentId: REQ } }]) {
+ const h = gate.screen({ method: 'POST', url: req.url, body: JSON.stringify(req.body) });
+ h.dispatching();
+ h.answered({ statusCode: 204, headers: {} });
+ }
+ });
+ const [done] = first.settle([{ token: created[0].token, observation: readOf(rowsOf('create')) }]);
+ assert.equal(done.verdict.action, 'commit');
+ const generation = open(dir).snapshot().envelope.groups.find((g) => g.family === 'customApi').generation;
+ const store = open(dir);
+ const ctx = createManagedCreateContext({ store, approvals: [], notFoundCode: NOT_FOUND });
+ const attempts = ctx.begin([planOf(rowsOf('update', NEW_ROWS), generation)]);
+ return { store, ctx, attempts, token: attempts[0].token };
+}
+
+/**
+ * The synthetic driver: it prepared `root` (a PATCH of the API under `ifMatch`, or none) and `children` (the new rows'
+ * exact bodies), and classifies a constituent as its prepared row — returning what it prepared, which the gate compares
+ * with what the request carries.
+ */
+function driver(token, { root = rootBody(), ifMatch = HELD, children = [reqBody(), respBody()] } = {}) {
+ const KINDS = {
+ customapirequestparameters: { kind: 'customApiRequestParameter', pk: 'customapirequestparameterid', keyOf: (b) => JSON.stringify([API_KEY, `request:${b.uniquename}`]) },
+ customapiresponseproperties: { kind: 'customApiResponseProperty', pk: 'customapiresponsepropertyid', keyOf: (b) => JSON.stringify([API_KEY, `response:${b.uniquename}`]) },
+ };
+ return ({ method, url, body }) => {
+ const p = apiPath(url);
+ let json;
+ try { json = JSON.parse(body); } catch { return null; }
+ if (method === 'PATCH' && p === `customapis(${API})` && root) {
+ return { type: 'rows', token, expectTable: 'customapis', expectKey: 'customapiid', rows: [{ kind: 'customApi', key: API_KEY, id: API, parentId: null, ...sentProjection(root) }], prepared: root, ifMatch };
+ }
+ const k = method === 'POST' ? KINDS[p] : null;
+ const prepared = k && children.find((c) => c[k.pk] === json[k.pk]);
+ if (!prepared) return null;
+ const { '[email protected]': bind, ...fields } = prepared;
+ return { type: 'rows', token, expectTable: p, expectKey: k.pk, rows: [{ kind: k.kind, key: k.keyOf(prepared), id: prepared[k.pk], parentId: API, ...sentProjection(fields) }], prepared };
+ };
+}
+
+// The edit's attempt as the store file holds it, read by a fresh handle.
+const attemptOn = (dir) => JSON.parse(JSON.stringify(open(dir).snapshot().envelope.attempts.find((a) => a.family === 'customApi')));
+const dispatchedOf = (a) => a.rowProtocol.rows.filter((r) => r.dispatched).map((r) => r.id).sort();
+const swallow = (p) => p.then((v) => v, (e) => e);
+const CT = { 'Content-Type': `multipart/mixed;boundary=${BATCH_ID}` };
+
+async function harness({ respond, drive } = {}) {
+ const dir = makeTempDir('mc-batch-');
+ const { store, ctx, attempts, token } = await boundEdit(dir);
+ const gate = createDeferredManagedCreateGate();
+ gate.bind(store);
+ const sent = [];
+ const request = async (req) => {
+ sent.push({ method: req.method, url: req.url, body: req.body, attempt: attemptOn(dir) });
+ return respond ? respond(req, sent.length) : answer(200, [rootPart(1), reqPart(2), respPart(3)]);
+ };
+ const client = createAzHttpClient(ENV, { getToken: () => 'TOK', request, sleep: async () => {}, workflowEffectGate: gate });
+ const set = { store, entries: attempts.map(({ token: t, epoch }) => ({ token: t, epoch })), classify: driver(token, drive), batch: { apiBase: API9, solution: SOL } };
+ const post = (text, headers = CT, url = BATCH_URL) => client.postRaw(url, text, { headers });
+ return { dir, store, ctx, attempts, token, sent, set, post, before: attemptOn(dir) };
+}
+
+const outcomes = (facts) => facts.filter((f) => f.type === 'row').map((f) => [f.contentId, f.id, f.outcome, f.status]);
+
+test('the captured change set — the API\'s PATCH and one new request parameter — is sealed once, sent once and acknowledged by its 200 and 201 bodies', async () => {
+ const h = await harness({ drive: { children: [reqBody()] }, respond: () => answer(200, [rootPart(1), reqPart(2)]) });
+ const out = await runWithManagedCreateSet(h.set, () => h.post(changeset([rootOp(), reqOp()])));
+ assert.equal(out.localError, null);
+ assert.equal(out.error, null);
+ assert.equal(h.sent.length, 1, 'one request left');
+ const atSend = h.sent[0].attempt;
+ assert.deepEqual(dispatchedOf(atSend), [API, NEW_REQ].sort(), 'both rows were sealed before the request left; the unsent child was not');
+ assert.equal(atSend.sendWindow.possible, h.before.sendWindow.possible + 1, 'the change set counts as one possible send');
+ const sealed = atSend.rowProtocol.rows.find((r) => r.id === NEW_REQ);
+ assert.deepEqual(sealed.sentFields, Object.keys(reqBody()).filter((k) => k !== '[email protected]').sort());
+ assert.ok(!JSON.stringify(atSend).includes('changeset_'), 'no request text is kept');
+ assert.deepEqual(outcomes(out.facts), [[1, API, 'acknowledged', 200], [2, NEW_REQ, 'acknowledged', 201]]);
+ assert.ok(out.facts.every((f) => f.batchStatus === 200 && !f.changesetFailure));
+});
+
+test('the API\'s PATCH, new request parameters and new response properties in the SDK\'s order are read by Content-ID, not position', async () => {
+ const h = await harness({ respond: () => answer(200, [respPart(3), rootPart(1), reqPart(2)]) });
+ const out = await runWithManagedCreateSet(h.set, () => h.post(changeset([rootOp(), reqOp(), respOp()])));
+ assert.equal(out.localError, null);
+ assert.deepEqual(dispatchedOf(h.sent[0].attempt), [API, NEW_REQ, NEW_RESP].sort());
+ assert.deepEqual(outcomes(out.facts), [[1, API, 'acknowledged', 200], [2, NEW_REQ, 'acknowledged', 201], [3, NEW_RESP, 'acknowledged', 201]]);
+});
+
+test('children only, of both kinds, in LF and quoted boundaries: admitted and acknowledged by 201 parts with no root part', async () => {
+ const h = await harness({ drive: { root: null }, respond: () => answer(200, [reqPart(1), respPart(2)], { eol: '\n', boundary: `Content-Type: multipart/mixed; boundary="${RC_ID}"` }) });
+ const text = changeset([reqOp(), respOp()], { eol: '\n', boundary: `Content-Type: multipart/mixed; boundary="${CS_ID}"` });
+ const out = await runWithManagedCreateSet(h.set, () => h.post(text, { 'content-type': `multipart/mixed; boundary="${BATCH_ID}"` }));
+ assert.equal(out.localError, null);
+ assert.deepEqual(dispatchedOf(h.sent[0].attempt), [NEW_REQ, NEW_RESP].sort(), 'the bound API is not sealed: it is not written');
+ assert.deepEqual(outcomes(out.facts), [[1, NEW_REQ, 'acknowledged', 201], [2, NEW_RESP, 'acknowledged', 201]]);
+});
+
+test('every other $batch is refused unsent, nothing is sealed, and the refusal is the set\'s local failure', async () => {
+ const h = await harness();
+ const ok = changeset([rootOp(), reqOp(), respOp()]);
+ const cases = {
+ 'mixed line endings': ok.replace('\r\nContent-ID: 2', '\nContent-ID: 2'),
+ 'a bare CR': ok.replace('Content-ID: 2', 'Content-ID: 2\r'),
+ 'a preamble': `preamble\r\n${ok}`,
+ 'an epilogue': `${ok}\r\n`,
+ 'a tab': ok.replace('Prefer: return=representation', 'Prefer:\treturn=representation'),
+ 'no closing change set delimiter': ok.replace(`--${CS_ID}--\r\n`, ''),
+ 'a second change set': ok.replace(`--${BATCH_ID}--`, `--${BATCH_ID}\r\nContent-Type: multipart/mixed;boundary=${CS_ID}\r\n\r\n--${CS_ID}--\r\n--${BATCH_ID}--`),
+ 'a nested multipart part': changeset([rootOp(), reqOp({ ...reqBody() }, { mime: [`Content-Type: multipart/mixed;boundary=${CS_ID}`, 'Content-Transfer-Encoding: binary', 'Content-ID: 2'] }), respOp()]),
+ 'a boundary inside a body': changeset([rootOp(), reqOp(reqBody({ description: `--${CS_ID}` })), respOp()]),
+ 'a duplicate MIME header': changeset([rootOp(), reqOp(reqBody(), { mime: ['Content-Type: application/http', 'Content-Transfer-Encoding: binary', 'Content-ID: 2', 'content-id: 2'] }), respOp()]),
+ 'a duplicate HTTP header': changeset([rootOp(), reqOp(reqBody(), { headers: ['Content-Type: application/json;type=entry', `MSCRM.SolutionUniqueName: ${SOL}`, 'Prefer: return=representation', 'prefer: return=representation'] }), respOp()]),
+ 'a folded header': changeset([rootOp(), reqOp(reqBody(), { headers: ['Content-Type: application/json;type=entry', `MSCRM.SolutionUniqueName: ${SOL}`, 'Prefer:', ' return=representation'] }), respOp()]),
+ 'an extra header': changeset([rootOp(), reqOp(reqBody(), { headers: ['Content-Type: application/json;type=entry', `MSCRM.SolutionUniqueName: ${SOL}`, 'Prefer: return=representation', 'MSCRM.BypassCustomPluginExecution: true'] }), respOp()]),
+ 'a duplicate JSON key': changeset([rootOp(), reqOp(null, { text: JSON.stringify(reqBody()).replace('"uniquename":"Extra"', '"uniquename":"Extra","uniquename":"Other"') }), respOp()]),
+ 'a nested JSON value': changeset([rootOp(rootBody({ description: { text: 'x' } })), reqOp(), respOp()]),
+ 'a duplicate Content-ID': changeset([rootOp(), reqOp(reqBody(), { contentId: 1 }), respOp()]),
+ 'a Content-ID gap': changeset([rootOp(), reqOp(reqBody(), { contentId: 3 }), respOp(respBody(), { contentId: 4 })]),
+ 'an extra query': changeset([rootOp(rootBody(), { path: `customapis(${API})?$select=customapiid&$expand=CustomAPIRequestParameters` }), reqOp(), respOp()]),
+ 'a content-id reference': changeset([rootOp(), reqOp(reqBody({ '[email protected]': '$1' })), respOp()]),
+ 'another API version': changeset([rootOp(), reqOp(reqBody(), { base: `${ENV}/api/data/v9.2` }), respOp()]),
+ 'another origin': changeset([rootOp(), reqOp(reqBody(), { base: 'https://fabrikam.crm.dynamics.com/api/data/v9.0' }), respOp()]),
+ 'a part the set did not prepare': changeset([rootOp(), reqOp(), respOp(), respOp(respBody({ customapiresponsepropertyid: OTHER, uniquename: 'More' }))]),
+ 'a GET': changeset([rootOp(), { method: 'GET', path: `customapis(${API})`, text: '' }, respOp()]),
+ 'a DELETE': changeset([rootOp(), { method: 'DELETE', path: `customapirequestparameters(${REQ})`, text: '' }, respOp()]),
+ 'a child PATCH': changeset([rootOp(), { method: 'PATCH', path: `customapirequestparameters(${REQ})?$select=customapirequestparameterid`, body: { displayname: 'x' }, etag: HELD }, respOp()]),
+ 'a root create': changeset([{ method: 'POST', path: 'customapis?$select=customapiid', body: { customapiid: API, uniquename: API_KEY } }, reqOp(), respOp()]),
+ 'another table': changeset([rootOp(), { method: 'POST', path: 'duplicateruleconditions', body: { duplicateruleconditionid: OTHER } }, respOp()]),
+ 'another bind': changeset([rootOp(), reqOp(reqBody({ '[email protected]': `/customapis(${OTHER})` })), respOp()]),
+ 'children bound to two APIs': changeset([reqOp(), respOp(respBody({ '[email protected]': `/customapis(${OTHER})` }))]),
+ 'another child id': changeset([rootOp(), reqOp(reqBody({ customapirequestparameterid: REQ })), respOp()]),
+ 'the SDK\'s order reversed': changeset([rootOp(), respOp(respBody(), { contentId: 2 }), reqOp(reqBody(), { contentId: 3 })]),
+ 'a root PATCH after a child': changeset([reqOp(reqBody(), { contentId: 1 }), rootOp(rootBody(), { contentId: 2 })]),
+ 'a wildcard If-Match': changeset([rootOp(rootBody(), { etag: '*' }), reqOp(), respOp()]),
+ 'a stale If-Match': changeset([rootOp(rootBody(), { etag: 'W/"14860001"' }), reqOp(), respOp()]),
+ 'no If-Match': changeset([rootOp(rootBody(), { etag: null }), reqOp(), respOp()]),
+ 'an If-Match on a child': changeset([rootOp(), reqOp(reqBody(), { etag: HELD }), respOp()]),
+ 'an unprepared root field': changeset([rootOp(rootBody({ isfunction: true })), reqOp(), respOp()]),
+ 'an unprepared root value': changeset([rootOp(rootBody({ isprivate: false })), reqOp(), respOp()]),
+ 'an extra child field': changeset([rootOp(), reqOp(reqBody({ iscustomizable: true })), respOp()]),
+ 'an unprepared child value': changeset([rootOp(), reqOp(reqBody({ description: 'Changed' })), respOp()]),
+ 'a mistyped child field': changeset([rootOp(), reqOp(reqBody({ type: '10' })), respOp()]),
+ 'no solution header': changeset([rootOp(), reqOp(reqBody(), { headers: ['Content-Type: application/json;type=entry', 'Prefer: return=representation'] }), respOp()]),
+ 'another solution': changeset([rootOp(), reqOp(reqBody(), { headers: ['Content-Type: application/json;type=entry', 'MSCRM.SolutionUniqueName: other_solution', 'Prefer: return=representation'] }), respOp()]),
+ 'a lone child': changeset([reqOp()]),
+ 'a lone root PATCH': changeset([rootOp()]),
+ };
+ const refused = async (text, headers = CT, url = BATCH_URL) => {
+ const out = await runWithManagedCreateSet(h.set, () => swallow(h.post(text, headers, url)));
+ return out.localError && out.localError.code;
+ };
+ for (const [name, text] of Object.entries(cases)) assert.equal(await refused(text), MISMATCH, name);
+ assert.equal(await refused(ok, { 'Content-Type': `multipart/mixed;boundary=${BATCH_ID.replace('0001', '0009')}` }), MISMATCH, 'another outer boundary');
+ assert.equal(await refused(ok, { ...CT, 'MSCRM.SolutionUniqueName': SOL }), MISMATCH, 'an extra outer header');
+ assert.equal(await refused(ok, CT, `${API9}/$batch?continue-on-error=true`), MISMATCH, 'a query on the batch');
+ assert.equal(await refused(ok, CT, `${ENV}/api/data/v9.2/$batch`), MISMATCH, 'another API base');
+ assert.equal(h.sent.length, 0, 'nothing left');
+ assert.deepEqual(attemptOn(h.dir), h.before, 'nothing was sealed or counted');
+ // The control: the same text is admitted.
+ const good = await runWithManagedCreateSet(h.set, () => h.post(ok));
+ assert.equal(good.localError, null);
+ assert.equal(h.sent.length, 1);
+});
+
+test('shapes from outside the admitted family stay refused: a duplicate rule\'s compound update, the hand-made failing change set, any $batch without the option', async () => {
+ const h = await harness();
+ const rule = changeset([
+ { method: 'POST', path: 'CompoundUpdateDuplicateDetectionRule', headers: ['Content-Type: application/json;type=entry', `MSCRM.SolutionUniqueName: ${SOL}`], body: { Entity: { '@odata.type': 'Microsoft.Dynamics.CRM.duplicaterule', duplicateruleid: OTHER }, ChildEntities: [] } },
+ { method: 'POST', path: 'duplicateruleconditions', headers: ['Content-Type: application/json;type=entry', `MSCRM.SolutionUniqueName: ${SOL}`], body: { duplicateruleconditionid: NEW_REQ, operatorcode: 0, '[email protected]': `/duplicaterules(${OTHER})` } },
+ ]);
+ // The hand-made change set of the captured failure: its PATCH has no If-Match and no $select, its POST no $select or Prefer.
+ const handMade = changeset([
+ { method: 'PATCH', path: `customapis(${API})`, headers: ['Content-Type: application/json;type=entry', `MSCRM.SolutionUniqueName: ${SOL}`], body: { isprivate: false } },
+ { method: 'POST', path: 'customapirequestparameters', headers: ['Content-Type: application/json;type=entry', `MSCRM.SolutionUniqueName: ${SOL}`], body: reqBody() },
+ ]);
+ for (const text of [rule, handMade]) {
+ const out = await runWithManagedCreateSet(h.set, () => swallow(h.post(text)));
+ assert.equal(out.localError.code, MISMATCH);
+ }
+ const { batch, ...without } = h.set;
+ assert.ok(batch);
+ const out = await runWithManagedCreateSet(without, () => swallow(h.post(changeset([rootOp(), reqOp(), respOp()]))));
+ assert.equal(out.localError.code, MISMATCH);
+ assert.match(out.localError.message, /sends each change on its own/, 'a set that did not opt in refuses as before');
+ assert.equal(h.sent.length, 0);
+ assert.deepEqual(attemptOn(h.dir), h.before);
+ assert.throws(() => batchConfig({ apiBase: `${API9}/`, solution: SOL }), TypeError);
+ assert.throws(() => batchConfig({ apiBase: API9 }), TypeError, 'the solution header is stated, never assumed');
+ await assert.rejects(runWithManagedCreateSet({ ...h.set, batch: { apiBase: 'http://contoso.crm.dynamics.com/api/data/v9.0', solution: null } }, async () => null), TypeError);
+});
+
+test('a constituent the driver describes otherwise, or under an edit that would create the API, is refused unsent', async () => {
+ const h = await harness();
+ const ok = changeset([rootOp(), reqOp(), respOp()]);
+ const run = async (classify) => {
+ const out = await runWithManagedCreateSet({ ...h.set, classify }, () => swallow(h.post(ok)));
+ return out.localError && out.localError.code;
+ };
+ const base = driver(h.token);
+ const tweak = (fn) => (req) => { const c = base(req); return c && fn(c, req); };
+ assert.equal(await run(tweak((c) => ({ ...c, token: 'another' }))), MISMATCH, 'another attempt');
+ assert.equal(await run(tweak((c) => ({ ...c, expectTable: 'customapis', expectKey: 'customapiid' }))), MISMATCH, 'another table to read the answer under');
+ assert.equal(await run(tweak((c) => ({ ...c, rows: [...c.rows, c.rows[0]] }))), MISMATCH, 'more than one row');
+ assert.equal(await run(tweak((c) => ({ ...c, rows: [{ ...c.rows[0], parentId: c.rows[0].parentId ? OTHER : null }] }))), MISMATCH, 'another parent');
+ assert.equal(await run(tweak((c) => ({ ...c, rows: [{ ...c.rows[0], sentSha256: H('0') }] }))), MISMATCH, 'a seal of another projection');
+ assert.equal(await run(tweak((c) => ({ ...c, rows: [{ ...c.rows[0], sentFields: ['iscustomizable'] }] }))), MISMATCH, 'a seal of a field not carried');
+ assert.equal(await run(tweak((c) => (c.ifMatch ? { ...c, ifMatch: 'W/"1"' } : c))), MISMATCH, 'a version the driver does not hold');
+ assert.equal(h.sent.length, 0);
+ assert.deepEqual(attemptOn(h.dir), h.before);
+ // A plan whose API row is a create: the change set would write an API the set has not bound.
+ const dir = makeTempDir('mc-batch-');
+ const store = open(dir);
+ const ctx = createManagedCreateContext({ store, approvals: [], notFoundCode: NOT_FOUND });
+ const [fresh] = ctx.begin([planOf(rowsOf('create', NEW_ROWS))]);
+ const gate = createDeferredManagedCreateGate();
+ gate.bind(store);
+ const handle = await runWithManagedCreateSet({ store, entries: [{ token: fresh.token, epoch: fresh.epoch }], classify: driver(fresh.token), batch: h.set.batch }, async () => {
+ try { gate.screen({ method: 'POST', url: BATCH_URL, body: ok, headers: CT }); } catch (e) { return e.code; }
+ return null;
+ });
+ assert.equal(handle.value, MISMATCH);
+});
+
+test('one seal, one send: no transport or SDK re-send, and a swallowed refusal stops the set', async () => {
+ for (const [name, respond, status] of [
+ ['a 503', () => ({ statusCode: 503, headers: {}, body: '' }), 503],
+ ['a 401', () => ({ statusCode: 401, headers: {}, body: '' }), 401],
+ ['a transport failure', () => ({ error: 'socket hang up', code: 'ECONNRESET' }), null],
+ ]) {
+ const h = await harness({ respond });
+ const text = changeset([rootOp(), reqOp(), respOp()]);
+ const out = await runWithManagedCreateSet(h.set, async () => {
+ await swallow(h.post(text));
+ // The SDK, or a caller, sends the same change set again.
+ return swallow(h.post(text));
+ });
+ assert.equal(h.sent.length, 1, `${name}: sent once`);
+ assert.equal(out.value.code, MISMATCH, `${name}: the second send is refused`);
+ assert.ok(out.facts.every((f) => f.outcome === 'unknown' && f.status === null && f.batchStatus === status), name);
+ assert.equal(attemptOn(h.dir).sendWindow.possible, h.before.sendWindow.possible + 1, `${name}: counted once`);
+ assert.deepEqual(dispatchedOf(attemptOn(h.dir)), [API, NEW_REQ, NEW_RESP].sort(), `${name}: the seals stay`);
+ }
+ const h = await harness();
+ const out = await runWithManagedCreateSet(h.set, async () => {
+ const first = await swallow(h.post(changeset([rootOp(rootBody({ isprivate: false })), reqOp(), respOp()])));
+ const second = await swallow(h.post(changeset([rootOp(), reqOp(), respOp()])));
+ return [first.code, second.code];
+ });
+ assert.deepEqual(out.value, [MISMATCH, MISMATCH]);
+ assert.match(out.localError.message, /part 1/, 'the first refusal is the one surfaced');
+ assert.equal(h.sent.length, 0);
+});
+
+test('the captured atomic failure, a failure inside a 200, a contradiction or a lost answer acknowledges nothing and is never re-sent', async () => {
+ const run = async (respond) => {
+ const h = await harness({ respond });
+ const out = await runWithManagedCreateSet(h.set, () => swallow(h.post(changeset([rootOp(), reqOp(), respOp()]))));
+ assert.equal(h.sent.length, 1);
+ return out.facts;
+ };
+ const rolledBack = await run(() => answer(412, [failedPart(2)]));
+ assert.deepEqual(outcomes(rolledBack), [[1, API, 'unknown', null], [2, NEW_REQ, 'unknown', 412], [3, NEW_RESP, 'unknown', null]]);
+ assert.ok(rolledBack.every((f) => f.batchStatus === 412 && JSON.stringify(f.changesetFailure) === JSON.stringify({ contentId: 2, status: 412, code: '0x80040333' })));
+ assert.ok(!JSON.stringify(rolledBack).includes('duplicate'), 'no answer text is kept');
+ const inner = await run(() => answer(200, [rootPart(1), { ...failedPart(2) }, respPart(3)]));
+ assert.deepEqual(inner.map((f) => f.outcome), ['unknown', 'unknown', 'unknown']);
+ assert.ok(inner.every((f) => !f.changesetFailure));
+ const swapped = await run(() => answer(200, [rootPart(1), reqPart(2, { customapirequestparameterid: OTHER }), respPart(3)]));
+ assert.deepEqual(swapped.map((f) => f.outcome), ['unknown', 'conflict', 'unknown']);
+ assert.equal(swapped[1].answeredId, OTHER);
+ const lostSuffix = await run(() => ({ ...answer(200, [rootPart(1), reqPart(2), respPart(3)]), body: answerText([rootPart(1), reqPart(2), respPart(3)]).split(`--${RC_ID}--`)[0] }));
+ assert.deepEqual(lostSuffix.map((f) => f.outcome), ['unknown', 'unknown', 'unknown']);
+ const lost = await run(() => { throw new Error('socket closed'); });
+ assert.deepEqual(lost.map((f) => f.outcome), ['unknown', 'unknown', 'unknown']);
+ // An answer that never arrives while the operation runs: unknown, unanswered.
+ const h = await harness({ respond: () => new Promise(() => {}) });
+ const out = await runWithManagedCreateSet(h.set, async () => { h.post(changeset([rootOp(), reqOp(), respOp()])); });
+ assert.ok(out.facts.length === 3 && out.facts.every((f) => f.outcome === 'unknown' && f.unanswered === true));
+});
+
+test('an answer is read per constituent: anything but a complete success is unknown, and a contradiction is a conflict', () => {
+ const admitted = { apiBase: API9, boundId: API, constituents: [{ contentId: 1, role: 'root', id: API }, { contentId: 2, role: 'requestParameter', id: NEW_REQ }, { contentId: 3, role: 'responseProperty', id: NEW_RESP }] };
+ const read = (res) => readChangesetAnswer(res, admitted).parts.map((p) => p.outcome);
+ const all = ['acknowledged', 'acknowledged', 'acknowledged'];
+ const unknown = ['unknown', 'unknown', 'unknown'];
+ const parts = () => [rootPart(1), reqPart(2), respPart(3)];
+ assert.deepEqual(read(answer(200, parts())), all);
+ assert.deepEqual(read(answer(200, parts(), { eol: '\n' })), all, 'LF throughout');
+ assert.deepEqual(read({ statusCode: 200, headers: {}, body: Buffer.from(answerText(parts())) }), all, 'bytes, and no outer Content-Type');
+ const cases = {
+ 'an outer 204': [answer(204, parts()), unknown],
+ 'a missing part': [answer(200, [rootPart(1), reqPart(2)]), unknown],
+ 'a duplicate Content-ID': [answer(200, [rootPart(1), reqPart(2), reqPart(2)]), unknown],
+ 'a foreign Content-ID': [answer(200, [rootPart(1), reqPart(2), respPart(9)]), unknown],
+ 'another outer boundary': [{ ...answer(200, parts()), headers: { 'Content-Type': 'multipart/mixed; boundary=batchresponse_0a0a0a0a-0000-4000-8000-000000000009' } }, unknown],
+ 'two outer Content-Types': [{ ...answer(200, parts()), headers: { 'content-type': `multipart/mixed; boundary=${RB_ID}`, 'Content-Type': `multipart/mixed; boundary=${RB_ID}` } }, unknown],
+ 'mixed line endings': [{ ...answer(200, parts()), body: answerText(parts()).replace('\r\nContent-ID: 2', '\nContent-ID: 2') }, unknown],
+ 'an epilogue': [{ ...answer(200, parts()), body: `${answerText(parts())}trailer\r\n` }, unknown],
+ 'a duplicate part header': [answer(200, [rootPart(1, {}, [`ETag: ${SAVED}`, `etag: ${SAVED}`]), reqPart(2), respPart(3)]), unknown],
+ 'a root 204': [answer(200, [{ ...rootPart(1), status: 'HTTP/1.1 204 No Content', text: '' }, reqPart(2), respPart(3)]), unknown],
+ 'a child 200': [answer(200, [rootPart(1), { ...reqPart(2), status: 'HTTP/1.1 200 OK' }, respPart(3)]), unknown],
+ 'no etag in a body': [answer(200, [rootPart(1), reqPart(2, { '@odata.etag': undefined }), respPart(3)]), unknown],
+ 'a root ETag header other than its body': [answer(200, [rootPart(1, {}, ['ETag: W/"1"']), reqPart(2), respPart(3)]), unknown],
+ 'a duplicate body key': [answer(200, [rootPart(1), { ...reqPart(2), text: JSON.stringify(reqPart(2).body).replace('{', `{"customapirequestparameterid":"${OTHER}",`) }, respPart(3)]), unknown],
+ 'a context of another API base': [answer(200, [rootPart(1, { '@odata.context': 'https://fabrikam.crm.dynamics.com/api/data/v9.0/$metadata#customapis(customapiid)/$entity' }), reqPart(2), respPart(3)]), unknown],
+ 'an alternate-key identity header': [answer(200, [rootPart(1), reqPart(2, {}, [...PART_HEADERS, `OData-EntityId: ${API9}/customapirequestparameters(uniquename='Extra')`]), respPart(3)]), unknown],
+ 'no primary key': [answer(200, [rootPart(1, { customapiid: undefined }), reqPart(2), respPart(3)]), unknown],
+ 'a root body without its key, however well its OData-EntityId reads': [answer(200, [rootPart(1, { customapiid: undefined }, [`ETag: ${SAVED}`, `OData-EntityId: ${API9}/customapis(${API})`]), reqPart(2), respPart(3)]), unknown],
+ 'a child body without its key, however well its Location reads': [answer(200, [rootPart(1), reqPart(2, { customapirequestparameterid: undefined }, [...PART_HEADERS, `Location: ${API9}/customapirequestparameters(${NEW_REQ})`]), respPart(3)]), unknown],
+ 'a child key that is no id': [answer(200, [rootPart(1), reqPart(2, { customapirequestparameterid: 'Extra' }), respPart(3)]), unknown],
+ 'a context that did not select the key': [answer(200, [rootPart(1), reqPart(2, { '@odata.context': `${API9}/$metadata#customapirequestparameters/$entity` }), respPart(3)]), unknown],
+ 'a context that selected another column': [answer(200, [rootPart(1), reqPart(2, { '@odata.context': `${API9}/$metadata#customapirequestparameters(uniquename)/$entity` }), respPart(3)]), unknown],
+ 'a body without its key and a Location naming another row': [answer(200, [rootPart(1), reqPart(2, { customapirequestparameterid: undefined }, [...PART_HEADERS, `Location: ${API9}/customapirequestparameters(${OTHER})`]), respPart(3)]), ['unknown', 'conflict', 'unknown']],
+ 'a child naming another API': [answer(200, [rootPart(1), reqPart(2, { _customapiid_value: OTHER }), respPart(3)]), ['unknown', 'conflict', 'unknown']],
+ 'a child answered as the other child table': [answer(200, [rootPart(1), reqPart(2, { '@odata.context': `${API9}/$metadata#customapiresponseproperties(customapiresponsepropertyid)/$entity` }), respPart(3)]), ['unknown', 'conflict', 'unknown']],
+ 'a Location naming another row': [answer(200, [rootPart(1, {}, [`ETag: ${SAVED}`, `Location: ${API9}/customapis(${OTHER})`]), reqPart(2), respPart(3)]), ['conflict', 'unknown', 'unknown']],
+ 'a root answered under another id': [answer(200, [rootPart(1, { customapiid: OTHER }), reqPart(2), respPart(3)]), ['conflict', 'unknown', 'unknown']],
+ 'a conflict in an incomplete answer': [answer(200, [rootPart(1), reqPart(2, { customapirequestparameterid: OTHER })]), ['unknown', 'conflict', 'unknown']],
+ 'a failed part of another set': [answer(412, [{ ...failedPart(9) }]), unknown],
+ };
+ for (const [name, [res, want]] of Object.entries(cases)) assert.deepEqual(read(res), want, name);
+ assert.equal(readChangesetAnswer(answer(412, [failedPart(9)]), admitted).failure, undefined, 'a failure of a part the set did not send is no diagnostic');
+ assert.equal(readChangesetAnswer(answer(200, [rootPart(1), failedPart(2), respPart(3)]), admitted).failure, undefined, 'a failure under a 200 is not the atomic one');
+});
+
+test('a checked run keeps the children\'s acknowledgements and never receipts the API\'s PATCH as a created root', async () => {
+ const h = await harness();
+ const out = await h.ctx.run({ attempts: h.attempts, classify: h.set.classify, batch: h.set.batch, acceptResult: () => true }, () => h.post(changeset([rootOp(), reqOp(), respOp()])));
+ assert.equal(out.checked, true);
+ assert.deepEqual(h.ctx.facts(h.token).map((f) => [f.id, f.mode, f.outcome]), [[API, 'update', 'acknowledged'], [NEW_REQ, 'create', 'acknowledged'], [NEW_RESP, 'create', 'acknowledged']]);
+ assert.ok(!attemptOn(h.dir).acknowledgedRoot, 'an edit of a bound API is no root create');
+ const failed = await harness({ respond: () => answer(412, [failedPart(2)]) });
+ const bad = await failed.ctx.run({ attempts: failed.attempts, classify: failed.set.classify, batch: failed.set.batch, acceptResult: () => true }, () => swallow(failed.post(changeset([rootOp(), reqOp(), respOp()]))));
+ assert.equal(bad.checked, false);
+ assert.ok(failed.ctx.facts(failed.token).every((f) => f.outcome === 'unknown'));
+ assert.ok(!attemptOn(failed.dir).acknowledgedRoot);
+ // A child answered without its own key in its body, though its Location names it: nothing is acknowledged, and the
+ // exact fresh read that follows cannot turn the answer into a child-create receipt or created ownership.
+ const keyless = await harness({ respond: () => answer(200, [rootPart(1), reqPart(2, { customapirequestparameterid: undefined }, [...PART_HEADERS, `Location: ${API9}/customapirequestparameters(${NEW_REQ})`]), respPart(3)]) });
+ const run = await keyless.ctx.run({ attempts: keyless.attempts, classify: keyless.set.classify, batch: keyless.set.batch, acceptResult: () => true }, () => keyless.post(changeset([rootOp(), reqOp(), respOp()])));
+ assert.equal(run.checked, false);
+ assert.deepEqual(keyless.ctx.facts(keyless.token).map((f) => f.outcome), ['unknown', 'unknown', 'unknown']);
+ const receipts = [];
+ const noteSaved = keyless.store.noteSaved;
+ keyless.store.noteSaved = (token, details) => {
+ receipts.push(...((details && details.acknowledgedChildCreates) || []).map((c) => c.id));
+ return noteSaved(token, details);
+ };
+ const [settled] = keyless.ctx.settle([{ token: keyless.token, observation: readOf(rowsOf('update', NEW_ROWS)) }]);
+ assert.notEqual(settled.verdict.action, 'commit');
+ assert.deepEqual(receipts, []);
+ const group = open(keyless.dir).snapshot().envelope.groups.find((g) => g.family === 'customApi');
+ assert.ok(!group.records.some((r) => r.id === NEW_REQ || r.id === NEW_RESP), 'no created binding for a child the answer did not prove');
+});
+
+test('the request reader alone: the captured request reads as the API\'s edit and one new child; the hand-made one does not', () => {
+ const config = batchConfig({ apiBase: API9, solution: SOL });
+ const parsed = parseCustomApiChangeset({ url: BATCH_URL, body: changeset([rootOp(), reqOp()]), headers: CT }, config, { limit: 4 });
+ assert.equal(parsed.boundId, API);
+ assert.deepEqual(parsed.constituents.map((k) => [k.contentId, k.role, k.id, k.ifMatch]), [[1, 'root', API, HELD], [2, 'requestParameter', NEW_REQ, undefined]]);
+ assert.throws(() => parseCustomApiChangeset({ url: BATCH_URL, body: changeset([rootOp(), reqOp(), respOp()]), headers: CT }, config, { limit: 2 }), { code: MISMATCH }, 'never read past what the set prepared');
+ const unsolved = batchConfig({ apiBase: API9, solution: null });
+ const noSolution = changeset([reqOp(reqBody(), { headers: ['Content-Type: application/json;type=entry', 'Prefer: return=representation'] }), respOp(respBody(), { headers: ['Content-Type: application/json;type=entry', 'Prefer: return=representation'] })]);
+ assert.equal(parseCustomApiChangeset({ url: BATCH_URL, body: noSolution, headers: CT }, unsolved).constituents.length, 2, 'no solution header when the SDK context has none');
+ assert.throws(() => parseCustomApiChangeset({ url: BATCH_URL, body: changeset([reqOp(), respOp()]), headers: CT }, unsolved), { code: MISMATCH }, 'and none added');
+ // Ordinary spaces around the boundary parameter's '=' are its grammar, as the client's own multipart reader reads it;
+ // anything more than spaces, or a second parameter, is still refused.
+ const spaced = (decl) => parseCustomApiChangeset({ url: BATCH_URL, body: changeset([rootOp(), reqOp()], { boundary: `Content-Type: ${decl}` }), headers: { 'Content-Type': `multipart/mixed; boundary = ${BATCH_ID}` } }, config);
+ assert.equal(spaced(`multipart/mixed; boundary = "${CS_ID}"`).constituents.length, 2);
+ assert.equal(spaced(`multipart/mixed;boundary =${CS_ID}`).constituents.length, 2);
+ for (const decl of [`multipart/mixed; boundary =\t"${CS_ID}"`, `multipart/mixed; boundary = "${CS_ID}"; charset=utf-8`, `multipart/mixed; boundary = "${CS_ID}`, `multipart/mixed; boundary = ""`]) {
+ assert.throws(() => spaced(decl), { code: MISMATCH }, decl);
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/managed-create-context.test.js b/plugins/model-apps/scripts/tests/managed-create-context.test.js
new file mode 100644
index 000000000..4af581328
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/managed-create-context.test.js
@@ -0,0 +1,579 @@
+'use strict';
+// The generic lifecycle of a protected create set (lib/managed-create-context.js) over the real binding store and the
+// real request boundary: prepare -> send in scope -> fresh read -> receipts -> commit, and the read-only recovery of an
+// attempt an earlier run left pending. A "new process" is a new context over a freshly opened store: it shares the
+// persisted attempt, never the earlier process's in-memory answers.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { createDeferredManagedCreateGate, sentProjection } = require('../lib/managed-create-transport.js');
+const { CODES, createManagedCreateContext, buildRowPlan, defaultApprovalToken, acceptSaved } = require('../lib/managed-create-context.js');
+const { CODES: STORE } = require('../lib/managed-bindings.js');
+const { createAzHttpClient } = require('../lib/sdk-http-client.js');
+const { H, API, REQ, API_KEY, REQ_KEY, URL_API, URL_MEMBER, open, codeOf, apiBody, apiClassifier } = require('./helpers/managed-rows.js');
+
+const NOT_FOUND = 'configuration-row-not-found';
+const OTHER = '77777777-7777-4777-8777-777777777777';
+const API2 = '44444444-4444-4444-8444-444444444444';
+const REQ2 = '55555555-5555-4555-8555-555555555555';
+const EV = '66666666-6666-4666-8666-666666666666';
+const EVV = '88888888-8888-4888-8888-888888888888';
+const ROOT_TOKEN = `adopt:customApi:${API_KEY}`;
+const CHILD_TOKEN = 'adopt:customApiRequestParameter:contoso_api/request%3Ap';
+
+const ctxOf = (dir, approvals = []) => createManagedCreateContext({ store: open(dir), approvals, notFoundCode: NOT_FOUND });
+
+/** The driver plan of one Custom API and its request parameter (buildRowPlan input). */
+function apiPlanOf({ key = API_KEY, api = API, req = REQ, mode = 'create', baseGeneration = null, baseObservation } = {}) {
+ return {
+ family: 'customApi', key, baseGeneration, declarationSha256: H('e'), ...(baseObservation !== undefined ? { baseObservation } : {}),
+ rows: [
+ { kind: 'customApi', key, id: api, parentId: null, mode, expectedSha256: H('7') },
+ { kind: 'customApiRequestParameter', key: JSON.stringify([key, 'request:p']), id: req, parentId: api, mode, expectedSha256: H('8') },
+ ],
+ members: [{ kind: 'customApi', id: api, componentType: 10134 }, { kind: 'customApiRequestParameter', id: req, componentType: 10135 }],
+ effects: [{ kind: 'membership', id: api }, { kind: 'membership', id: req }],
+ };
+}
+
+/** A fresh read of apiPlanOf exactly as planned; `over` replaces fields of a row by kind. */
+function apiRead({ key = API_KEY, api = API, req = REQ, root = {}, child = {}, members = 'present' } = {}) {
+ return {
+ rows: [
+ { kind: 'customApi', key, id: api, state: 'present', parentId: null, projectionSha256: H('7'), ...root },
+ { kind: 'customApiRequestParameter', key: JSON.stringify([key, 'request:p']), id: req, state: 'present', parentId: api, projectionSha256: H('8'), ...child },
+ ],
+ members: [{ id: api, state: members }, { id: req, state: 'present' }],
+ ruleState: null,
+ };
+}
+
+// Send the deep insert (and the two memberships) of the attempts through the real gate, answered as `answer` says.
+async function send(ctx, store, attempts, { classify, answer = { statusCode: 204, headers: {} }, body = apiBody(), members = [API, REQ], accept = () => true } = {}) {
+ const gate = createDeferredManagedCreateGate();
+ gate.bind(store);
+ const exchange = (req) => {
+ const h = gate.screen(req);
+ h.dispatching();
+ h.answered(answer);
+ };
+ return ctx.run({ attempts, classify: classify || apiClassifier(attempts[0].token), acceptResult: accept }, async () => {
+ exchange({ method: 'POST', url: URL_API, body: JSON.stringify(body) });
+ for (const id of members) exchange({ method: 'POST', url: URL_MEMBER, body: JSON.stringify({ ComponentId: id }) });
+ });
+}
+
+// A context whose store is reachable, for the gate.
+function begun(dir, plans = [apiPlanOf()], approvals = []) {
+ const store = open(dir);
+ const ctx = createManagedCreateContext({ store, approvals, notFoundCode: NOT_FOUND });
+ return { store, ctx, attempts: ctx.begin(plans) };
+}
+
+const groupOf = (dir, key = API_KEY) => open(dir).snapshot().envelope.groups.find((g) => g.family === 'customApi' && g.key === key) || null;
+const attemptsOf = (dir) => open(dir).snapshot().envelope.attempts;
+
+test('a set sent, acknowledged and read back exactly is committed as created, row by row, with its proof and baseline', async () => {
+ const dir = makeTempDir('mc-context-');
+ const { store, ctx, attempts } = begun(dir);
+ const out = await send(ctx, store, attempts);
+ assert.equal(out.localError, null);
+ const [result] = ctx.settle([{ token: attempts[0].token, observation: apiRead() }]);
+ assert.equal(result.verdict.action, 'commit');
+ const g = groupOf(dir);
+ assert.deepEqual(g.records.map((r) => [r.kind, r.key, r.id, r.origin, r.parentKey]), [
+ ['customApi', API_KEY, API, 'created', undefined], ['customApiRequestParameter', REQ_KEY, REQ, 'created', API_KEY]]);
+ assert.deepEqual(g.consumerState.rows.map((r) => [r.kind, r.projectionSha256]), [['customApi', H('7')], ['customApiRequestParameter', H('8')]]);
+ assert.equal(attemptsOf(dir).length, 0);
+});
+
+test('a parent\'s acknowledgement never mints a child: the child needs its own exact approval', async () => {
+ const dir = makeTempDir('mc-context-');
+ const { store, ctx, attempts } = begun(dir);
+ const token = attempts[0].token;
+ // The driver sends the root on its own; the parameter appears by other means.
+ const rootOnly = ({ body }) => ({ type: 'rows', token, expectTable: 'customapis', expectKey: 'customapiid', rows: [{ kind: 'customApi', key: API_KEY, id: JSON.parse(body).customapiid, parentId: null, ...sentProjection({ uniquename: API_KEY }) }] });
+ await send(ctx, store, attempts, { classify: rootOnly, members: [] });
+ const [halted] = ctx.settle([{ token, observation: apiRead() }]);
+ assert.equal(halted.verdict.code, CODES.ownership);
+ assert.deepEqual(halted.verdict.approvals, [CHILD_TOKEN], 'only the child is asked for; the root kept its receipt');
+ const [done] = ctxOf(dir, [CHILD_TOKEN]).settle([{ token, observation: apiRead(), declarationSha256: H('e') }]);
+ assert.equal(done.verdict.action, 'commit');
+ assert.deepEqual(groupOf(dir).records.map((r) => r.origin), ['created', 'adopted']);
+});
+
+test('recovery: a changed declaration halts; a prepared attempt resumes first; a sending one proven unsent resumes continue', () => {
+ const dir = makeTempDir('mc-context-');
+ const { prepare, expected } = buildRowPlan(apiPlanOf());
+ const store = open(dir);
+ const [prepared] = store.prepareAttemptSet([prepare]);
+ const ctx = ctxOf(dir);
+ assert.equal(ctx.classify(prepared, apiRead(), { declarationSha256: H('f') }).code, CODES.intentChanged);
+ assert.deepEqual(ctx.classify(prepared, apiRead(), { declarationSha256: H('e') }), { action: 'resume', claim: 'first' });
+ const [first] = ctx.resume([{ token: prepared, claim: 'first' }]);
+ assert.deepEqual(first.expected, expected, 'a resumed prepared attempt gets the same proof again');
+ const later = ctxOf(dir);
+ assert.deepEqual(later.classify(prepared, { rows: [], members: [] }, { declarationSha256: H('e') }), { action: 'resume', claim: 'continue' });
+ const [cont] = later.resume([{ token: prepared, claim: 'continue' }]);
+ assert.ok(cont.epoch !== first.epoch, 'a continued attempt runs under a new epoch');
+});
+
+test('recovery after a possible send: an unread row or member is unverified, never absent', async () => {
+ const dir = makeTempDir('mc-context-');
+ const { store, ctx, attempts } = begun(dir);
+ await send(ctx, store, attempts);
+ const later = ctxOf(dir);
+ const at = { declarationSha256: H('e') };
+ assert.equal(later.classify(attempts[0].token, apiRead({ child: { state: 'unknown' } }), at).code, CODES.unverified);
+ assert.equal(later.classify(attempts[0].token, apiRead({ members: 'unknown' }), at).code, CODES.unverified);
+ assert.equal(later.classify(attempts[0].token, { rows: apiRead().rows.slice(0, 1), members: apiRead().members }, at).code, CODES.unverified, 'a row the read does not list is unknown');
+});
+
+test('recovery: another id, parent or content, or an answer naming another id, is a conflict; a missing row or member is completion', async () => {
+ const dir = makeTempDir('mc-context-');
+ const { store, ctx, attempts } = begun(dir);
+ await send(ctx, store, attempts, { answer: { statusCode: 204, headers: { 'OData-EntityId': `${URL_API}(${OTHER})` } } });
+ const token = attempts[0].token;
+ assert.equal(ctx.classify(token, apiRead()).code, CODES.conflict, 'this process saw the service answer another id');
+ const later = ctxOf(dir);
+ const at = { declarationSha256: H('e') };
+ assert.equal(later.classify(token, apiRead({ child: { projectionSha256: H('0') } }), at).code, CODES.conflict);
+ assert.equal(later.classify(token, apiRead({ child: { parentId: OTHER } }), at).code, CODES.conflict);
+ const absent = later.classify(token, apiRead({ child: { state: 'absent' } }), at);
+ assert.deepEqual([absent.code, absent.phase, absent.rows.map((r) => r.key)], [CODES.completion, 'saved', [REQ_KEY]]);
+ const member = later.classify(token, apiRead({ members: 'absent' }), at);
+ assert.deepEqual([member.code, member.phase], [CODES.completion, 'membership-pending']);
+});
+
+test('recovery in a later process: an exact set nobody acknowledged needs each row\'s exact approval, and is then adopted', async () => {
+ const dir = makeTempDir('mc-context-');
+ const { store, ctx, attempts } = begun(dir);
+ // Nobody checked what the operation answered, so no answer of it acknowledges a create.
+ await send(ctx, store, attempts, { accept: null });
+ const token = attempts[0].token;
+ const halted = ctxOf(dir).classify(token, apiRead(), { declarationSha256: H('e') });
+ assert.deepEqual([halted.code, halted.approvals], [CODES.ownership, [ROOT_TOKEN, CHILD_TOKEN]]);
+ assert.equal(ctxOf(dir, [ROOT_TOKEN]).classify(token, apiRead(), { declarationSha256: H('e') }).code, CODES.ownership, 'the root\'s approval does not cover the child');
+ const [done] = ctxOf(dir, [ROOT_TOKEN, CHILD_TOKEN]).settle([{ token, observation: apiRead(), declarationSha256: H('e') }]);
+ assert.equal(done.verdict.action, 'commit');
+ assert.deepEqual(groupOf(dir).records.map((r) => r.origin), ['adopted', 'adopted']);
+});
+
+test('receipts outlive the process that proved them: a later run asks only for the row it could not prove', async () => {
+ const dir = makeTempDir('mc-context-');
+ const { store, ctx, attempts } = begun(dir);
+ await send(ctx, store, attempts);
+ const token = attempts[0].token;
+ const [first] = ctx.settle([{ token, observation: apiRead({ child: { state: 'unknown' } }) }]);
+ assert.equal(first.verdict.code, CODES.unverified);
+ assert.equal(attemptsOf(dir)[0].acknowledgedRoot, true, 'the root create this process saw acknowledged and read exactly is kept');
+ const halted = ctxOf(dir).classify(token, apiRead(), { declarationSha256: H('e') });
+ assert.deepEqual(halted.approvals, [CHILD_TOKEN]);
+});
+
+test('a bound row found absent halts with the driver\'s not-found code and is never replaced', async () => {
+ const dir = makeTempDir('mc-context-');
+ const one = begun(dir);
+ await send(one.ctx, one.store, one.attempts);
+ one.ctx.settle([{ token: one.attempts[0].token, observation: apiRead() }]);
+ const edit = apiPlanOf({ mode: 'update', baseGeneration: groupOf(dir).generation, baseObservation: { rowVersion: '1', savedSha256: H('1') } });
+ const two = begun(dir, [edit]);
+ await send(two.ctx, two.store, two.attempts, { members: [] });
+ const gone = two.ctx.classify(two.attempts[0].token, apiRead({ root: { state: 'absent' } }));
+ assert.deepEqual([gone.code, gone.rows.map((r) => r.id)], [NOT_FOUND, [API]]);
+ const [kept] = two.ctx.settle([{ token: two.attempts[0].token, observation: apiRead() }]);
+ assert.equal(kept.verdict.action, 'commit', 'an edit of bound rows commits on their existing bindings');
+ assert.deepEqual(groupOf(dir).records.map((r) => r.origin), ['created', 'created']);
+});
+
+test('a private input is proved by this process\'s own answer and a matching read; across processes only by approval; masked never', async () => {
+ const EV_KEY = 'contoso_ev';
+ const VAL_KEY = JSON.stringify([EV_KEY, 'value']);
+ const plan = {
+ family: 'environmentVariable', key: EV_KEY, declarationSha256: H('e'),
+ rows: [
+ { kind: 'environmentVariable', key: EV_KEY, id: EV, parentId: null, mode: 'create', expectedSha256: H('7') },
+ { kind: 'environmentVariableValue', key: VAL_KEY, id: EVV, parentId: EV, mode: 'create', expectedSha256: H('8'), sensitiveInput: true },
+ ],
+ members: [{ kind: 'environmentVariable', id: EV, componentType: 380 }],
+ };
+ const read = (privateState) => ({
+ rows: [
+ { kind: 'environmentVariable', key: EV_KEY, id: EV, state: 'present', parentId: null, projectionSha256: H('7') },
+ { kind: 'environmentVariableValue', key: VAL_KEY, id: EVV, state: 'present', parentId: EV, projectionSha256: H('8'), ...(privateState ? { privateState } : {}) },
+ ],
+ members: [{ id: EV, state: 'present' }],
+ ruleState: null,
+ });
+ const evClassify = (token) => ({ body }) => {
+ const b = JSON.parse(body);
+ return { type: 'rows', token, expectTable: 'environmentvariabledefinitions', expectKey: 'environmentvariabledefinitionid', rows: [
+ { kind: 'environmentVariable', key: EV_KEY, id: b.id, parentId: null, ...sentProjection({ schemaname: EV_KEY }) },
+ { kind: 'environmentVariableValue', key: VAL_KEY, id: EVV, parentId: b.id, ...sentProjection({ schemaname: EV_KEY }) }] };
+ };
+ const run = async () => {
+ const dir = makeTempDir('mc-context-');
+ const b = begun(dir, [plan]);
+ await send(b.ctx, b.store, b.attempts, { classify: evClassify(b.attempts[0].token), body: { id: EV }, members: [] });
+ return { dir, ...b, token: b.attempts[0].token };
+ };
+ const same = await run();
+ const [mine] = same.ctx.settle([{ token: same.token, observation: read('match') }]);
+ assert.equal(mine.verdict.action, 'commit');
+ const valueToken = `adopt:environmentVariableValue:${EV_KEY}/value`;
+ const cross = await run();
+ const at = { declarationSha256: H('e') };
+ assert.equal(cross.ctx.classify(cross.token, read('masked')).code, CODES.completion, 'a masked value is never certified');
+ assert.equal(cross.ctx.classify(cross.token, read()).code, CODES.completion, 'an unreported private state is not a match');
+ // The definition's create was receipted by its checked run; its private value still needs the maker's approval.
+ const halted = ctxOf(cross.dir).classify(cross.token, read('match'), at);
+ assert.deepEqual([halted.code, halted.approvals], [CODES.ownership, [valueToken]]);
+ assert.equal(ctxOf(cross.dir, [`adopt:environmentVariable:${EV_KEY}`, valueToken]).classify(cross.token, read('masked'), at).code, CODES.completion, 'approval never certifies a masked value');
+ const [adopted] = ctxOf(cross.dir, [`adopt:environmentVariable:${EV_KEY}`, valueToken]).settle([{ token: cross.token, observation: read('match'), declarationSha256: H('e') }]);
+ assert.equal(adopted.verdict.action, 'commit');
+ // A receipt from an earlier process proves the row was created, not that its private value is today's: a later
+ // process that reads the value matching still needs the maker's approval of it.
+ const earlier = await run();
+ assert.equal(earlier.ctx.settle([{ token: earlier.token, observation: read('masked') }])[0].verdict.code, CODES.completion);
+ const later = ctxOf(earlier.dir).classify(earlier.token, read('match'), at);
+ assert.deepEqual([later.code, later.approvals], [CODES.ownership, [valueToken]]);
+});
+
+test('approval tokens are percent-encoded, so a / or : in a key never makes two rows share one', () => {
+ const child = (root, slot) => ({ kind: 'customApiRequestParameter', key: JSON.stringify([root, slot]), parentId: API });
+ assert.equal(defaultApprovalToken('customApi', 'a/b:c', child('a/b:c', 'request:x/y')), 'adopt:customApiRequestParameter:a%2Fb%3Ac/request%3Ax%2Fy');
+ assert.notEqual(defaultApprovalToken('customApi', 'a/b', child('a/b', 'c')), defaultApprovalToken('customApi', 'a', child('a', 'b/c')));
+ assert.equal(defaultApprovalToken('customApi', 'a/b', { kind: 'customApi', key: 'a/b', parentId: null }), 'adopt:customApi:a/b');
+ assert.throws(() => defaultApprovalToken('customApi', 'a', { kind: 'customApiRequestParameter', key: 'a/request:p', parentId: API }), TypeError);
+ assert.throws(() => defaultApprovalToken('customApi', 'a', child('b', 'p')), TypeError, 'a child of another root has no token under this one');
+ assert.throws(() => createManagedCreateContext({ store: open(makeTempDir('mc-context-')) }), TypeError, 'a driver must name its not-found code');
+});
+
+test('each item of a set settles on its own: one halting never holds back another\'s commit', async () => {
+ const dir = makeTempDir('mc-context-');
+ const KEY2 = 'contoso_api2';
+ const { store, ctx, attempts } = begun(dir, [apiPlanOf(), apiPlanOf({ key: KEY2, api: API2, req: REQ2 })]);
+ const tokenOf = new Map([[API_KEY, attempts[0].token], [KEY2, attempts[1].token], [API, attempts[0].token], [REQ, attempts[0].token], [API2, attempts[1].token], [REQ2, attempts[1].token]]);
+ const both = (req) => { const c = apiClassifier(null)(req); return c && { ...c, token: tokenOf.get(c.type === 'rows' ? c.rows[0].key : c.id) }; };
+ await send(ctx, store, attempts, { classify: both });
+ await send(ctx, store, attempts, { classify: both, body: { ...apiBody(API2, REQ2), uniquename: KEY2 }, members: [API2, REQ2] });
+ const results = ctx.settle([
+ { token: attempts[0].token, observation: apiRead({ child: { state: 'unknown' } }) },
+ { token: attempts[1].token, observation: apiRead({ key: KEY2, api: API2, req: REQ2 }) }]);
+ assert.deepEqual(results.map((r) => r.verdict.action === 'commit' ? 'commit' : r.verdict.code), [CODES.unverified, 'commit']);
+ assert.ok(groupOf(dir, KEY2));
+ assert.equal(groupOf(dir), null);
+ assert.deepEqual(attemptsOf(dir).map((a) => [a.key, a.acknowledgedRoot]), [[API_KEY, true]], 'the halted item keeps its attempt and the receipt this process proved');
+});
+
+// One request through a bound gate inside a context's run, answered as `answer` says (null: dispatched, never answered).
+function exchangeVia(gate, req, answer) {
+ const h = gate.screen(req);
+ h.dispatching();
+ if (answer) h.answered(answer);
+}
+const OK = { statusCode: 204, headers: {} };
+const deepInsert = (body = apiBody()) => ({ method: 'POST', url: URL_API, body: JSON.stringify(body) });
+const membership = (id) => ({ method: 'POST', url: URL_MEMBER, body: JSON.stringify({ ComponentId: id }) });
+function gateOf(store) {
+ const gate = createDeferredManagedCreateGate();
+ gate.bind(store);
+ return gate;
+}
+
+test('only a checked run acknowledges a create: no check, a failed check, a thrown or refused operation, or any unproven row answer keeps every 2xx unchecked', async () => {
+ const runs = [
+ ['no result check', {}, async () => 'saved'],
+ ['the check says no', { acceptResult: () => false }, async () => 'saved'],
+ ['the check throws', { acceptResult: () => { throw new Error('malformed'); } }, async () => 'saved'],
+ ['the check answers a truthy non-true', { acceptResult: () => 1 }, async () => 'saved'],
+ ['the operation failed after its content was acknowledged', { acceptResult: () => true }, async () => { throw new Error('a later step of the push failed'); }],
+ ];
+ for (const [name, opts, after] of runs) {
+ const dir = makeTempDir('mc-context-');
+ const { store, ctx, attempts } = begun(dir);
+ const gate = gateOf(store);
+ const out = await ctx.run({ attempts, classify: apiClassifier(attempts[0].token), ...opts }, async () => {
+ exchangeVia(gate, deepInsert(), OK);
+ for (const id of [API, REQ]) exchangeVia(gate, membership(id), OK);
+ return after();
+ });
+ assert.equal(out.checked, false, name);
+ assert.deepEqual(ctx.facts(attempts[0].token).filter((f) => f.type === 'row').map((f) => f.outcome), ['unchecked', 'unchecked'], name);
+ assert.equal(attemptsOf(dir)[0].acknowledgedRoot, false, `${name}: no root receipt`);
+ const [halted] = ctx.settle([{ token: attempts[0].token, observation: apiRead() }]);
+ assert.deepEqual([halted.verdict.code, halted.verdict.approvals], [CODES.ownership, [ROOT_TOKEN, CHILD_TOKEN]], `${name}: nothing is taken as created`);
+ }
+ // A 2xx for another row is kept a conflict, and an unknown answer stays unknown: neither is laundered by the check.
+ const dir = makeTempDir('mc-context-');
+ const { store, ctx, attempts } = begun(dir);
+ const gate = gateOf(store);
+ const out = await ctx.run({ attempts, classify: apiClassifier(attempts[0].token), acceptResult: () => true }, async () => {
+ exchangeVia(gate, deepInsert(), { statusCode: 204, headers: { 'OData-EntityId': `${URL_API}(${OTHER})` } });
+ return { saved: true };
+ });
+ assert.equal(out.checked, false);
+ assert.deepEqual(ctx.facts(attempts[0].token).map((f) => f.outcome), ['conflict', 'conflict']);
+ assert.equal(ctx.classify(attempts[0].token, apiRead()).code, CODES.conflict);
+ const lost = begun(makeTempDir('mc-context-'));
+ const lostGate = gateOf(lost.store);
+ const l = await lost.ctx.run({ attempts: lost.attempts, classify: apiClassifier(lost.attempts[0].token), acceptResult: () => true }, async () => { exchangeVia(lostGate, deepInsert(), null); return { saved: true }; });
+ assert.equal(l.checked, false, 'an unanswered content request is never laundered by saved:true');
+ assert.deepEqual(lost.ctx.facts(lost.attempts[0].token).map((f) => [f.outcome, f.unanswered]), [['unknown', true], ['unknown', true]]);
+});
+
+test('a checked run receipts its new root before anything else: the attempt stays sending, its membership still goes, and its open debt is kept', async () => {
+ const dir = makeTempDir('mc-context-');
+ const { store, ctx, attempts } = begun(dir);
+ const gate = gateOf(store);
+ const token = attempts[0].token;
+ const out = await ctx.run({ attempts, classify: apiClassifier(token), acceptResult: () => true }, async () => { exchangeVia(gate, deepInsert(), OK); return 'saved'; });
+ assert.equal(out.checked, true);
+ const [a] = attemptsOf(dir);
+ assert.deepEqual([a.acknowledgedRoot, a.phase, a.savedObservation, a.acknowledgedChildCreates], [true, 'sending', null, undefined], 'the root alone, before any read-back');
+ // The membership work comes after the receipt, and one of its answers is lost: the receipt stands, the debt stays.
+ const later = await ctx.run({ attempts, classify: apiClassifier(token), acceptResult: () => true }, async () => {
+ exchangeVia(gate, membership(API), OK);
+ exchangeVia(gate, membership(REQ), { statusCode: 500, headers: {} });
+ return 'saved';
+ });
+ assert.equal(later.localError, null);
+ const pending = ctxOf(dir).classify(token, apiRead({ members: 'absent' }), { declarationSha256: H('e') });
+ assert.deepEqual([pending.code, pending.phase], [CODES.completion, 'membership-pending']);
+ const owned = ctxOf(dir).classify(token, apiRead(), { declarationSha256: H('e') });
+ assert.deepEqual([owned.code, owned.approvals], [CODES.ownership, [CHILD_TOKEN]], 'a later process has the root receipt; the child needs its own proof');
+ // An edit never creates a root receipt, and the store refuses a receipt from another epoch.
+ assert.equal(codeOf(() => store.noteSaved(token, { proof: null, acknowledgedRoot: true, phase: 'sending', epoch: 99 })), STORE.pending);
+ assert.equal(codeOf(() => store.noteSaved(token, { proof: { x: 1 }, acknowledgedRoot: true, phase: 'sending', epoch: 1 })), STORE.notSettled);
+});
+
+test('an edit\'s checked run receipts no root', async () => {
+ const dir = makeTempDir('mc-context-');
+ const one = begun(dir);
+ await send(one.ctx, one.store, one.attempts);
+ one.ctx.settle([{ token: one.attempts[0].token, observation: apiRead() }]);
+ const two = begun(dir, [apiPlanOf({ mode: 'update', baseGeneration: groupOf(dir).generation, baseObservation: { rowVersion: '1', savedSha256: H('1') } })]);
+ const out = await send(two.ctx, two.store, two.attempts, { members: [] });
+ assert.equal(out.checked, true);
+ assert.equal(attemptsOf(dir)[0].acknowledgedRoot, false);
+ assert.equal(codeOf(() => two.store.noteSaved(two.attempts[0].token, { proof: null, acknowledgedRoot: true, phase: 'sending', epoch: 1 })), STORE.notSettled);
+});
+
+test('a receipt the store cannot write is the run\'s typed local failure, and nothing more is sent under that context', async () => {
+ const dir = makeTempDir('mc-context-');
+ const { store, ctx, attempts } = begun(dir);
+ const gate = gateOf(store);
+ const full = Object.assign(new Error('the managed binding store would be too large'), { code: STORE.storeFull });
+ store.noteSaved = () => { throw full; };
+ const out = await ctx.run({ attempts, classify: apiClassifier(attempts[0].token), acceptResult: () => true }, async () => { exchangeVia(gate, deepInsert(), OK); return 'saved'; });
+ assert.deepEqual([out.checked, out.localError], [false, full]);
+ assert.deepEqual(ctx.facts(attempts[0].token).map((f) => f.outcome), ['unchecked', 'unchecked']);
+ let called = false;
+ const next = await ctx.run({ attempts, classify: apiClassifier(attempts[0].token), acceptResult: () => true }, async () => { called = true; });
+ assert.deepEqual([called, next.localError, next.checked], [false, full, false]);
+});
+
+test('acceptSaved accepts only the SDK\'s saved result for exactly the pushed artifact', () => {
+ const ok = acceptSaved({ type: 'customApi', id: API });
+ assert.equal(ok({ type: 'customApi', id: API.toUpperCase(), saved: true, shipped: true, publish: { kind: 'notRequested' } }), true);
+ for (const r of [
+ { type: 'customApi', id: API, saved: false, adoptedExisting: true },
+ { type: 'customApi', id: API, saved: false, shipped: false, publish: { kind: 'notRequested' }, error: { code: 'ALREADY_EXISTS' } },
+ { type: 'customApi', id: API, saved: true, error: { code: 'VERSION_CONFLICT' } },
+ { type: 'customApi', id: API, saved: true, adoptedExisting: true },
+ { type: 'customApi', id: API, saved: 'true' },
+ { type: 'customApi', id: OTHER, saved: true },
+ { type: 'environmentVariable', id: API, saved: true },
+ null, 'saved', [],
+ ]) assert.equal(ok(r), false, JSON.stringify(r));
+ const command = acceptSaved({ type: 'command', id: 'account' });
+ assert.equal(command({ type: 'command', id: 'account', saved: true }), true);
+ assert.equal(command({ type: 'command', id: 'Account', saved: true }), false, 'a command bar is named by its table, exactly');
+ assert.equal(command({ type: 'command', id: API, saved: true }), false, 'never by one of its root GUIDs');
+ assert.throws(() => acceptSaved({ type: 'customApi' }), TypeError);
+});
+
+// A directory holding the committed set of apiPlanOf, as one checked run and an exact read leave it.
+async function committed() {
+ const dir = makeTempDir('mc-context-');
+ const one = begun(dir);
+ await send(one.ctx, one.store, one.attempts);
+ assert.equal(one.ctx.settle([{ token: one.attempts[0].token, observation: apiRead() }])[0].verdict.action, 'commit');
+ return dir;
+}
+const editOf = (dir, sha) => {
+ const plan = apiPlanOf({ mode: 'update', baseGeneration: groupOf(dir).generation, baseObservation: { rowVersion: '1', savedSha256: H('1') } });
+ plan.rows[0].expectedSha256 = sha;
+ return plan;
+};
+
+test('an edit of bound rows records the intent it proved, never another identity or origin', async () => {
+ const dir = await committed();
+ const two = begun(dir, [editOf(dir, H('c'))]);
+ await send(two.ctx, two.store, two.attempts, { members: [] });
+ const [done] = two.ctx.settle([{ token: two.attempts[0].token, observation: apiRead({ root: { projectionSha256: H('c') } }) }]);
+ assert.equal(done.verdict.action, 'commit');
+ assert.deepEqual(groupOf(dir).records.map((r) => [r.kind, r.id, r.origin, r.intentSha256]), [['customApi', API, 'created', H('c')], ['customApiRequestParameter', REQ, 'created', H('8')]]);
+ for (const recordOf of [
+ (row, origin, attempt, header) => ({ formatVersion: 1, ...header, kind: row.kind, key: row.key, id: OTHER, intentSha256: row.expectedSha256, origin, ...(row.parentId ? { parentKey: API_KEY } : {}) }),
+ (row, origin, attempt, header) => ({ formatVersion: 1, ...header, kind: row.kind, key: row.key, id: row.id, intentSha256: row.expectedSha256, origin: 'adopted', ...(row.parentId ? { parentKey: API_KEY } : {}) }),
+ ]) {
+ const d = await committed();
+ const store = open(d);
+ const ctx = createManagedCreateContext({ store, notFoundCode: NOT_FOUND, recordOf });
+ const attempts = ctx.begin([editOf(d, H('c'))]);
+ await send(ctx, store, attempts, { members: [] });
+ const before = groupOf(d);
+ assert.throws(() => ctx.settle([{ token: attempts[0].token, observation: apiRead({ root: { projectionSha256: H('c') } }) }]), TypeError);
+ assert.deepEqual(groupOf(d), before, 'nothing committed');
+ }
+});
+
+// A plan over rows that already exist and that this run never writes: every row an update, with the base it read.
+const readOnlyPlanOf = (over = {}) => apiPlanOf({ mode: 'update', baseObservation: { rowVersion: '1', savedSha256: H('1') }, ...over });
+
+test('a plan of existing rows that sent nothing is accepted read-only: each unbound row adopted under its own approval, in one write', () => {
+ const dir = makeTempDir('mc-context-');
+ const { ctx, attempts } = begun(dir, [readOnlyPlanOf()]);
+ const token = attempts[0].token;
+ const [capture] = ctx.captureReadOnly([token]);
+ const [halted] = ctx.acceptReadOnly([{ token, observation: apiRead(), capture }]);
+ assert.deepEqual([halted.verdict.code, halted.verdict.approvals, halted.group], [CODES.ownership, [ROOT_TOKEN, CHILD_TOKEN], undefined]);
+ assert.equal(groupOf(dir), null);
+ const before = attemptsOf(dir)[0];
+ const approved = createManagedCreateContext({ store: open(dir), approvals: [ROOT_TOKEN, CHILD_TOKEN], notFoundCode: NOT_FOUND });
+ const [fresh] = approved.captureReadOnly([token]);
+ // The store accepts nothing unsent as created, whatever proposal a driver hands it.
+ const s = open(dir);
+ const real = s.commitReadOnlyGroupSet;
+ const created = [];
+ const spy = createManagedCreateContext({ store: Object.assign(Object.create(s), { commitReadOnlyGroupSet: (p) => { created.push(...p); throw new Error('held'); } }), approvals: [ROOT_TOKEN, CHILD_TOKEN], notFoundCode: NOT_FOUND });
+ assert.throws(() => spy.acceptReadOnly([{ token, observation: apiRead(), capture: fresh, declarationSha256: H('e') }]), /held/);
+ assert.equal(codeOf(() => real.call(s, created.map((p) => ({ ...p, records: p.records.map((r) => ({ ...r, origin: 'created' })) })))), STORE.adoptionRequired);
+ assert.equal(groupOf(dir), null);
+ const [done] = approved.acceptReadOnly([{ token, observation: apiRead(), capture: fresh, declarationSha256: H('e') }]);
+ assert.equal(done.verdict.action, 'commit');
+ assert.deepEqual(groupOf(dir).records.map((r) => [r.kind, r.id, r.origin]), [['customApi', API, 'adopted'], ['customApiRequestParameter', REQ, 'adopted']]);
+ assert.equal(done.group.generation, groupOf(dir).generation);
+ assert.deepEqual(attemptsOf(dir), []);
+ assert.deepEqual([before.acknowledgedRoot, before.rowProtocol.rows.map((r) => r.dispatched), before.rowProtocol.effects.map((e) => e.dispatched)], [false, [false, false], [false, false]], 'nothing was sent, and nothing claims it was');
+});
+
+test('a read-only acceptance keeps a bound row\'s origin and refuses anything else: a create plan, no capture, a store moved since the capture, a dispatch', async () => {
+ const dir = await committed();
+ const bound = begun(dir, [readOnlyPlanOf({ baseGeneration: groupOf(dir).generation })]);
+ const [cap] = bound.ctx.captureReadOnly([bound.attempts[0].token]);
+ const [kept] = bound.ctx.acceptReadOnly([{ token: bound.attempts[0].token, observation: apiRead(), capture: cap }]);
+ assert.equal(kept.verdict.action, 'commit');
+ assert.deepEqual(groupOf(dir).records.map((r) => r.origin), ['created', 'created'], 'bound rows keep how they were first bound');
+
+ const create = begun(makeTempDir('mc-context-'));
+ const [cc] = create.ctx.captureReadOnly([create.attempts[0].token]);
+ assert.throws(() => create.ctx.acceptReadOnly([{ token: create.attempts[0].token, observation: apiRead(), capture: cc }]), TypeError, 'a create plan is never accepted without its send');
+ const plain = begun(makeTempDir('mc-context-'), [readOnlyPlanOf()], [ROOT_TOKEN, CHILD_TOKEN]);
+ assert.throws(() => plain.ctx.acceptReadOnly([{ token: plain.attempts[0].token, observation: apiRead() }]), TypeError, 'no capture, no acceptance');
+
+ // The attempt moved between the capture and the acceptance: another process claimed it under a new epoch. Nothing
+ // is written; a write to another group alone moves nothing this acceptance rests on.
+ const moved = makeTempDir('mc-context-');
+ const m = begun(moved, [readOnlyPlanOf()], [ROOT_TOKEN, CHILD_TOKEN]);
+ const [mc] = m.ctx.captureReadOnly([m.attempts[0].token]);
+ begun(moved, [apiPlanOf({ key: 'contoso_api2', api: API2, req: REQ2 })]);
+ assert.deepEqual(m.ctx.captureReadOnly([m.attempts[0].token]), [mc]);
+ ctxOf(moved).resume([{ token: m.attempts[0].token, claim: 'continue' }]);
+ const snap = open(moved).snapshot().envelope;
+ assert.equal(codeOf(() => m.ctx.acceptReadOnly([{ token: m.attempts[0].token, observation: apiRead(), capture: mc }])), STORE.conflict);
+ assert.deepEqual(open(moved).snapshot().envelope, snap);
+
+ // Something was dispatched under the attempt: it may have written, so it is recovered, never accepted read-only.
+ const sent = makeTempDir('mc-context-');
+ const s = begun(sent, [readOnlyPlanOf()], [ROOT_TOKEN, CHILD_TOKEN]);
+ // The proposal the context would hand the store while nothing was sent, kept to hand it again after the dispatch.
+ const real = s.store.commitReadOnlyGroupSet;
+ let proposals;
+ s.store.commitReadOnlyGroupSet = (p) => { proposals = p; throw new Error('held'); };
+ assert.throws(() => s.ctx.acceptReadOnly([{ token: s.attempts[0].token, observation: apiRead(), capture: s.ctx.captureReadOnly([s.attempts[0].token])[0] }]), /held/);
+ s.store.commitReadOnlyGroupSet = real;
+ const gate = gateOf(s.store);
+ await s.ctx.run({ attempts: s.attempts, classify: apiClassifier(s.attempts[0].token) }, async () => exchangeVia(gate, membership(API), null));
+ const [sc] = s.ctx.captureReadOnly([s.attempts[0].token]);
+ const [refused] = s.ctx.acceptReadOnly([{ token: s.attempts[0].token, observation: apiRead(), capture: sc }]);
+ assert.deepEqual([refused.verdict.code, refused.group], [STORE.pending, undefined]);
+ assert.equal(groupOf(sent), null);
+ // The store refuses the same acceptance on its own, should a driver hand it a dispatched attempt.
+ assert.equal(codeOf(() => s.store.commitReadOnlyGroupSet(proposals.map((p) => ({ ...p, capture: sc })))), STORE.pending);
+ assert.equal(groupOf(sent), null);
+});
+
+test('a read-only acceptance is all or nothing: one item not accepted holds every other item too', () => {
+ const dir = makeTempDir('mc-context-');
+ const KEY2 = 'contoso_api2';
+ const { ctx, attempts } = begun(dir, [readOnlyPlanOf(), readOnlyPlanOf({ key: KEY2, api: API2, req: REQ2 })], [ROOT_TOKEN, CHILD_TOKEN]);
+ const captures = ctx.captureReadOnly(attempts.map((a) => a.token));
+ const results = ctx.acceptReadOnly([
+ { token: attempts[0].token, observation: apiRead(), capture: captures[0] },
+ { token: attempts[1].token, observation: apiRead({ key: KEY2, api: API2, req: REQ2 }), capture: captures[1] }]);
+ assert.deepEqual(results.map((r) => [r.verdict.action === 'commit' ? 'commit' : r.verdict.code, r.group]), [['commit', undefined], [CODES.ownership, undefined]]);
+ assert.equal(groupOf(dir), null, 'the accepted item is not committed alone');
+ assert.equal(attemptsOf(dir).length, 2);
+});
+test('an attempt that omits a bound row keeps that row\'s confirmed baseline, read-only or sent, and never restamps it as observed', async () => {
+ // A plan of the root alone over a committed group, and a read of that root alone.
+ const rootOnly = (dir, sha) => {
+ const plan = readOnlyPlanOf({ baseGeneration: groupOf(dir).generation });
+ plan.rows = [{ ...plan.rows[0], expectedSha256: sha }];
+ plan.members = [plan.members[0]];
+ plan.effects = [];
+ return plan;
+ };
+ const rootRead = (sha) => {
+ const o = apiRead({ root: { projectionSha256: sha } });
+ o.rows = [o.rows[0]];
+ return o;
+ };
+ const baselines = (dir) => groupOf(dir).consumerState.rows;
+
+ const quiet = await committed();
+ const [, child] = baselines(quiet);
+ const r = begun(quiet, [rootOnly(quiet, H('7'))]);
+ const [capture] = r.ctx.captureReadOnly([r.attempts[0].token]);
+ const [accepted] = r.ctx.acceptReadOnly([{ token: r.attempts[0].token, observation: rootRead(H('7')), capture }]);
+ assert.equal(accepted.verdict.action, 'commit');
+ assert.deepEqual(baselines(quiet).map((b) => [b.kind, b.projectionSha256]), [['customApi', H('7')], ['customApiRequestParameter', H('8')]]);
+ assert.deepEqual(baselines(quiet)[1], child, 'the omitted row keeps its baseline exactly');
+
+ const edited = await committed();
+ const [, before] = baselines(edited);
+ const s = begun(edited, [rootOnly(edited, H('c'))]);
+ const classify = (req) => {
+ const c = apiClassifier(s.attempts[0].token)(req);
+ return c && c.type === 'rows' ? { ...c, rows: [c.rows[0]] } : c;
+ };
+ await send(s.ctx, s.store, s.attempts, { classify, members: [] });
+ const [done] = s.ctx.settle([{ token: s.attempts[0].token, observation: rootRead(H('c')) }]);
+ assert.equal(done.verdict.action, 'commit');
+ assert.deepEqual(baselines(edited).map((b) => [b.kind, b.projectionSha256]), [['customApi', H('c')], ['customApiRequestParameter', H('8')]]);
+ assert.deepEqual(baselines(edited)[1], before, 'the omitted row keeps its baseline exactly');
+ assert.deepEqual(groupOf(edited).records.map((rec) => [rec.kind, rec.id, rec.origin]), [['customApi', API, 'created'], ['customApiRequestParameter', REQ, 'created']]);
+});
+
+test('a 2xx whose identity repeats a member name is never a create receipt, through the real client: no created binding', async () => {
+ const child = `"uniquename":"p","customapirequestparameterid":"${REQ}"`;
+ const bodies = [
+ `{"customapi\\u0069d":"${OTHER}","customapiid":"${API}"}`,
+ `{"customapiid":"${API}","CustomAPIRequestParameters":[{"customapirequestparameterid":"${OTHER}",${child}}]}`,
+ `{"customapiid":"${API}","CustomAPIRequestParameters":[{"uniquename":"p","customapirequestparameterid":"${OTHER}"}],"CustomAPIRequestParameters":[{${child}}]}`,
+ ];
+ for (const body of bodies) {
+ const dir = makeTempDir('mc-context-');
+ const { ctx, store, attempts } = begun(dir);
+ const gate = createDeferredManagedCreateGate();
+ gate.bind(store);
+ const client = createAzHttpClient('https://contoso.crm.dynamics.com', {
+ getToken: () => 'offline-token', workflowEffectGate: gate, sleep: async () => {}, request: async () => ({ statusCode: 201, headers: {}, body }),
+ });
+ const out = await ctx.run({ attempts, classify: apiClassifier(attempts[0].token), acceptResult: () => true }, () => client.post(URL_API, JSON.stringify(apiBody())));
+ const [done] = ctx.settle([{ token: attempts[0].token, observation: apiRead() }]);
+ assert.deepEqual([out.checked, done.verdict.code, done.group, groupOf(dir)], [false, CODES.ownership, undefined, null], body);
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/managed-create-transport.test.js b/plugins/model-apps/scripts/tests/managed-create-transport.test.js
new file mode 100644
index 000000000..f2b8dad86
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/managed-create-transport.test.js
@@ -0,0 +1,337 @@
+'use strict';
+// The send-once request boundary of a protected create set (lib/managed-create-transport.js), driven through the
+// plugin's real HTTP client (lib/sdk-http-client.js) with a fake transport: inert outside a set's scope; inside one,
+// every row is sealed in the store before its request leaves, sent at most once, and anything the set did not prepare —
+// an unbound gate, a DELETE, a `$batch`, an unclassified write, another id or parent, a fenced epoch — is refused unsent
+// and kept as the set's typed local failure, whatever the SDK does with the error.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { createAzHttpClient } = require('../lib/sdk-http-client.js');
+const { CODES } = require('../lib/managed-bindings.js');
+const { apiPath } = require('../lib/workflow-effect-context.js');
+const { MISMATCH, createDeferredManagedCreateGate, runWithManagedCreateSet, composeWriteGates, answerOf } = require('../lib/managed-create-transport.js');
+const { ENV, API, REQ, URL_API, URL_MEMBER, open, apiPlan, apiExpected, apiBody, apiClassifier } = require('./helpers/managed-rows.js');
+
+const OTHER = '77777777-7777-4777-8777-777777777777';
+
+// A store with one sending Custom API attempt, a gate bound to it, and a client whose every request is recorded with
+// what the store file said at the moment it left.
+function harness({ answer, bind = true } = {}) {
+ const dir = makeTempDir('mc-transport-');
+ const store = open(dir);
+ const [token] = store.prepareAttemptSet([apiPlan()]);
+ const [entry] = store.markAttemptSetSending([{ token, expected: apiExpected() }]);
+ const gate = createDeferredManagedCreateGate();
+ if (bind) gate.bind(store);
+ const sent = [];
+ const request = async (req) => {
+ sent.push({ method: req.method, url: req.url, disk: diskOf(dir) });
+ if (answer) return answer(req);
+ return { statusCode: 204, headers: { 'OData-EntityId': `${URL_API}(${API})` }, body: '' };
+ };
+ const client = createAzHttpClient(ENV, { getToken: () => 'TOK', request, sleep: async () => {}, workflowEffectGate: gate });
+ const set = { store, entries: [entry], classify: apiClassifier(token), deleteCode: 'configuration-protected-removal-unsupported' };
+ return { dir, store, token, entry, gate, client, sent, set };
+}
+// What the store file holds now, read by a fresh handle.
+const diskOf = (dir) => JSON.parse(JSON.stringify(open(dir).snapshot().envelope));
+const swallow = (p) => p.then(() => null, (e) => e);
+
+test('outside a create set the gate is inert, bound or not: every request is sent as before', async () => {
+ const h = harness({ bind: false });
+ await h.client.post(URL_API, apiBody());
+ await h.client.delete(`${URL_API}(${API})`);
+ assert.equal(h.sent.length, 2);
+ assert.equal(h.gate.screen({ method: 'POST', url: URL_API, body: '{}' }), null);
+});
+
+test('inside a set an unbound gate refuses every write unsent, and reads still pass', async () => {
+ const h = harness({ bind: false });
+ const out = await runWithManagedCreateSet(h.set, async () => {
+ await h.client.get(URL_API);
+ return swallow(h.client.post(URL_API, JSON.stringify(apiBody())));
+ });
+ assert.deepEqual(h.sent.map((s) => s.method), ['GET']);
+ assert.equal(out.localError.code, MISMATCH);
+ assert.equal(out.value, out.localError, 'the SDK saw the same typed error');
+});
+
+test('a DELETE, a $batch and an unclassified write are refused unsent; after one refusal nothing further is sent', async () => {
+ const h = harness();
+ const out = await runWithManagedCreateSet(h.set, async () => {
+ const del = await swallow(h.client.delete(`${URL_API}(${API})`));
+ const batch = await swallow(h.client.post(`${ENV}/api/data/v9.2/$batch`, '--b\r\n'));
+ const other = await swallow(h.client.patch(`${ENV}/api/data/v9.2/accounts(${OTHER})`, { name: 'x' }));
+ const later = await swallow(h.client.post(URL_API, JSON.stringify(apiBody())));
+ return [del, batch, other, later].map((e) => e && e.code);
+ });
+ assert.deepEqual(out.value, ['configuration-protected-removal-unsupported', MISMATCH, MISMATCH, MISMATCH]);
+ assert.equal(h.sent.length, 0);
+ assert.equal(out.localError.code, 'configuration-protected-removal-unsupported', 'the first local failure is the one surfaced');
+});
+
+test('a write the classifier does not recognise is refused even as the first request of the set', async () => {
+ const h = harness();
+ const out = await runWithManagedCreateSet(h.set, () => swallow(h.client.patch(`${ENV}/api/data/v9.2/accounts(${OTHER})`, { name: 'x' })));
+ assert.equal(out.localError.code, MISMATCH);
+ assert.equal(h.sent.length, 0);
+});
+
+test('every row of a request is sealed in the store before it leaves, sent once, and acknowledged in memory only', async () => {
+ const h = harness();
+ const out = await runWithManagedCreateSet(h.set, async () => {
+ await h.client.post(URL_API, JSON.stringify(apiBody()));
+ return swallow(h.client.post(URL_API, JSON.stringify(apiBody())));
+ });
+ assert.equal(h.sent.length, 1);
+ const rows = h.sent[0].disk.attempts[0].rowProtocol.rows;
+ assert.deepEqual(rows.map((r) => [r.dispatched, r.sentFields]), [[true, ['customapiid', 'uniquename']], [true, ['uniquename']]], 'sealed before the send');
+ assert.equal(h.sent[0].disk.attempts[0].sendWindow.possible, 1);
+ assert.equal(out.value.code, MISMATCH, 'the second send of the same rows is refused');
+ assert.deepEqual(out.facts.map((f) => [f.kind, f.outcome, f.status]), [['customApi', 'acknowledged', 204], ['customApiRequestParameter', 'acknowledged', 204]]);
+ assert.equal(diskOf(h.dir).attempts[0].acknowledgedRoot, false, 'an answer is never persisted as a receipt here');
+});
+
+test('a row under another id or another parent is refused before anything is written', async () => {
+ for (const body of [apiBody(API, OTHER), apiBody(API, undefined, OTHER)]) {
+ const h = harness();
+ const before = JSON.stringify(diskOf(h.dir));
+ const out = await runWithManagedCreateSet(h.set, () => swallow(h.client.post(URL_API, JSON.stringify(body))));
+ assert.equal(out.localError.code, MISMATCH);
+ assert.equal(h.sent.length, 0);
+ assert.equal(JSON.stringify(diskOf(h.dir)), before);
+ }
+});
+
+test('an answer naming another id is a conflict; a lost answer is unknown; neither is acknowledged', async () => {
+ const conflict = harness({ answer: () => ({ statusCode: 204, headers: { 'odata-entityid': `${URL_API}(${OTHER})` }, body: '' }) });
+ const c = await runWithManagedCreateSet(conflict.set, () => conflict.client.post(URL_API, JSON.stringify(apiBody())));
+ assert.deepEqual([c.facts[0].outcome, c.facts[0].answeredId], ['conflict', OTHER]);
+ const lost = harness({ answer: () => { throw Object.assign(new Error('socket hang up'), { code: 'ECONNRESET' }); } });
+ const l = await runWithManagedCreateSet(lost.set, () => swallow(lost.client.post(URL_API, JSON.stringify(apiBody()))));
+ assert.equal(lost.sent.length, 1, 'a send-once request is not re-sent after a transport failure');
+ assert.deepEqual(l.facts.map((f) => f.outcome), ['unknown', 'unknown']);
+ assert.equal(l.localError, null, 'a remote failure is not a local one');
+ assert.equal(answerOf({ statusCode: 201, headers: { Location: `${URL_API}(uniquename='contoso_api')` } }, API).outcome, 'unknown', 'an alternate-key answer names no id');
+ assert.equal(answerOf({ statusCode: 409, headers: {} }, API).outcome, 'unknown');
+});
+
+test('a run whose attempt was claimed by another since it began is fenced at the store: unsent, and its failure kept even when swallowed', async () => {
+ const h = harness();
+ open(h.dir).markAttemptSetSending([{ token: h.token, expected: apiExpected() }], { claim: 'continue' });
+ const out = await runWithManagedCreateSet(h.set, async () => { await swallow(h.client.post(URL_API, JSON.stringify(apiBody()))); return 'the SDK reported nothing'; });
+ assert.equal(h.sent.length, 0);
+ assert.equal(out.value, 'the SDK reported nothing');
+ assert.equal(out.localError.code, CODES.pending);
+});
+
+test('a completion effect is marked dispatched before it leaves and sent once', async () => {
+ const h = harness();
+ const out = await runWithManagedCreateSet(h.set, async () => {
+ await h.client.post(URL_MEMBER, JSON.stringify({ ComponentId: API, ComponentType: 10134 }));
+ return swallow(h.client.post(URL_MEMBER, JSON.stringify({ ComponentId: API, ComponentType: 10134 })));
+ });
+ assert.equal(h.sent.length, 1);
+ assert.equal(h.sent[0].disk.attempts[0].rowProtocol.effects.find((e) => e.id === API).dispatched, true);
+ assert.equal(out.value.code, MISMATCH);
+ assert.deepEqual(out.facts.map((f) => [f.type, f.kind, f.outcome]), [['effect', 'membership', 'acknowledged']]);
+});
+
+test('a request left running after its set ended is refused', async () => {
+ const h = harness();
+ let late;
+ await runWithManagedCreateSet(h.set, async () => { late = new Promise((resolve) => setImmediate(resolve)).then(() => swallow(h.client.post(URL_API, JSON.stringify(apiBody())))); });
+ assert.equal((await late).code, MISMATCH);
+ assert.equal(h.sent.length, 0);
+});
+
+test('composed gates: a request one gate owns keeps that gate\'s handle; two owners or any refusal send nothing', async () => {
+ const handle = { dispatching() {}, answered() {} };
+ const workflow = { screen: (req) => (req.url.endsWith('/workflows') ? handle : null) };
+ const h = harness();
+ const both = composeWriteGates(workflow, null, h.gate);
+ assert.equal(both.screen({ method: 'POST', url: `${ENV}/api/data/v9.2/workflows`, body: '{}' }), handle, 'outside a set the workflow gate alone decides');
+ assert.equal(both.screen({ method: 'POST', url: URL_API, body: '{}' }), null);
+ const out = await runWithManagedCreateSet(h.set, async () => {
+ const owned = both.screen({ method: 'POST', url: URL_API, body: JSON.stringify(apiBody()), headers: {} });
+ return typeof owned.dispatching;
+ });
+ assert.equal(out.value, 'function');
+ const greedy = { screen: () => handle };
+ const two = await runWithManagedCreateSet(harness().set, () => swallow(Promise.resolve().then(() => composeWriteGates(greedy, greedy).screen({ method: 'POST', url: URL_API }))));
+ assert.equal(two.value.code, MISMATCH);
+ assert.equal(two.localError, two.value);
+ const refusing = { screen: () => { throw Object.assign(new Error('no'), { code: 'managed-workflow-effect-mismatch' }); } };
+ assert.throws(() => composeWriteGates(refusing, h.gate).screen({ method: 'POST', url: URL_API }), { code: 'managed-workflow-effect-mismatch' });
+});
+
+test('the gate binds once, to one store', () => {
+ const a = harness();
+ assert.equal(a.gate.boundTo(a.store), true);
+ a.gate.bind(a.store);
+ assert.throws(() => a.gate.bind(open(makeTempDir('mc-transport-'))), /already bound/);
+ assert.throws(() => a.gate.bind({}), TypeError);
+});
+
+// The identity a protected Custom API create is answered under: its own row and the one request parameter it carries.
+const EXPECT = { id: API, table: 'customapis', key: 'customapiid', children: [{ id: REQ, at: 'CustomAPIRequestParameters', key: 'customapirequestparameterid', match: { uniquename: 'p' } }] };
+const at = (id = API, table = 'customapis') => `${ENV}/api/data/v9.2/${table}(${id})`;
+const child = (over = {}) => ({ uniquename: 'p', customapirequestparameterid: REQ, ...over });
+
+test('every identity an answer carries must agree with the prepared row: a second, folded or other-table header is never read past', () => {
+ const cases = [
+ ['one matching OData-EntityId', { statusCode: 204, headers: { 'OData-EntityId': at() }, body: '' }, 'acknowledged'],
+ ['OData-EntityId and Location agree', { statusCode: 204, headers: { 'odata-entityid': at(), LOCATION: at() } }, 'acknowledged'],
+ ['the key spelled as name=value', { statusCode: 204, headers: { 'odata-entityid': `${ENV}/api/data/v9.2/customapis(customapiid=${API})` } }, 'acknowledged'],
+ ['the empty 204 with no identity', { statusCode: 204, headers: {}, body: '' }, 'acknowledged'],
+ ['one header in two spellings', { statusCode: 204, headers: { 'OData-EntityId': at(), 'odata-entityid': at() } }, 'unknown'],
+ ['a header folded with a comma', { statusCode: 204, headers: { 'odata-entityid': `${at()}, ${at()}` } }, 'unknown'],
+ ['a header given as two values', { statusCode: 204, headers: { 'odata-entityid': [at(), at()] } }, 'unknown'],
+ ['an alternate-key URL', { statusCode: 204, headers: { Location: `${ENV}/api/data/v9.2/customapis(uniquename='contoso_api')` } }, 'unknown'],
+ ['an alternate key whose value happens to be the id', { statusCode: 204, headers: { 'odata-entityid': `${ENV}/api/data/v9.2/customapis(parentid=${API})` } }, 'unknown'],
+ ['a header that names no row', { statusCode: 204, headers: { Location: `${ENV}/api/data/v9.2/customapis` } }, 'unknown'],
+ ['a 202, which only queued the request', { statusCode: 202, headers: { 'odata-entityid': at() } }, 'unknown'],
+ ['a 201 with no identity at all', { statusCode: 201, headers: {} }, 'unknown'],
+ ['a 200 whose body names no key', { statusCode: 200, headers: {}, body: '{}' }, 'unknown'],
+ ['the first header agrees, the second names another row', { statusCode: 204, headers: { 'odata-entityid': at(), location: at(REQ) } }, 'conflict'],
+ ['a header under another table', { statusCode: 204, headers: { 'odata-entityid': at(API, 'accounts') } }, 'conflict'],
+ ['another row wins over a folded header', { statusCode: 204, headers: { 'odata-entityid': `${at()}, ${at()}`, location: at(REQ) } }, 'conflict'],
+ ];
+ for (const [name, res, want] of cases) assert.equal(answerOf(res, EXPECT).outcome, want, name);
+ assert.equal(answerOf({ statusCode: 204, headers: { location: at(REQ) } }, EXPECT).answeredId, REQ, 'the id that disagrees is the one reported');
+});
+
+test('a body is read for the prepared key and each named child only, and any doubt about it is unknown', () => {
+ const ok = { customapiid: API, uniquename: 'contoso_api', CustomAPIRequestParameters: [child()] };
+ const res = (body, headers = { 'odata-entityid': at() }) => ({ statusCode: 201, headers, body: typeof body === 'string' ? body : JSON.stringify(body) });
+ const cases = [
+ ['the body agrees with the header', res(ok), 'acknowledged'],
+ ['the body alone, as an object', { statusCode: 201, headers: {}, body: ok }, 'acknowledged'],
+ ['a lookup to another row is not an identity', res({ ...ok, _parentid_value: REQ }), 'acknowledged'],
+ ['no child array: the child is not answered for', res({ customapiid: API }), 'acknowledged'],
+ ['the body names another row', res({ ...ok, customapiid: REQ }), 'conflict'],
+ ['the child is answered under another id', res({ ...ok, CustomAPIRequestParameters: [child({ customapirequestparameterid: API })] }), 'conflict'],
+ ['the key twice in the text (JSON.parse keeps the last)', res(`{"customapiid":"${REQ}","customapiid":"${API}"}`), 'unknown'],
+ ['a key that is not a string', res({ ...ok, customapiid: 7 }), 'unknown'],
+ ['an OData error envelope under a 2xx', res({ error: { code: '0x80040217', message: 'no' } }), 'unknown'],
+ ['a body that is not JSON', res('<html/>'), 'unknown'],
+ ['a body that is an array', res([ok]), 'unknown'],
+ ['no child matches', res({ ...ok, CustomAPIRequestParameters: [] }), 'unknown'],
+ ['two children match', res({ ...ok, CustomAPIRequestParameters: [child(), child()] }), 'unknown'],
+ ['the child array is not an array', res({ ...ok, CustomAPIRequestParameters: {} }), 'unknown'],
+ ['the child id is not a GUID', res({ ...ok, CustomAPIRequestParameters: [child({ customapirequestparameterid: 'x' })] }), 'unknown'],
+ // Two members of one decoded name in an object the identity is read from: JSON.parse keeps only the last.
+ ['the key spelled twice, once escaped', res(`{"customapi\\u0069d":"${OTHER}","customapiid":"${API}"}`, {}), 'unknown'],
+ ['a child key twice', res(`{"customapiid":"${API}","CustomAPIRequestParameters":[{"customapirequestparameterid":"${OTHER}","uniquename":"p","customapirequestparameterid":"${REQ}"}]}`, {}), 'unknown'],
+ ['the child navigation property twice', res(`{"customapiid":"${API}","CustomAPIRequestParameters":[{"uniquename":"p","customapirequestparameterid":"${OTHER}"}],"CustomAPIRequestParameters":[{"uniquename":"p","customapirequestparameterid":"${REQ}"}]}`, {}), 'unknown'],
+ // What must not change: one escaped spelling alone, escapes inside a value, and a repeat in an expanded lookup.
+ ['the key spelled once, escaped', res(`{"customapi\\u0069d":"${API}"}`, {}), 'acknowledged'],
+ ['escaped quotes and backslashes inside a value', res(`{"description":"a \\"quoted\\" \\\\ name","customapiid":"${API}"}`, {}), 'acknowledged'],
+ ['a repeat inside an expanded lookup', res(`{"customapiid":"${API}","plugintypeid":{"name":"a","name":"b"},"CustomAPIRequestParameters":[{"uniquename":"p","customapirequestparameterid":"${REQ}"}]}`, {}), 'acknowledged'],
+ ];
+ for (const [name, r, want] of cases) assert.equal(answerOf(r, EXPECT).outcome, want, name);
+});
+
+test('a GUID is compared without regard to case, in a header, the body and a child, and another GUID is a conflict in any case', () => {
+ // GUIDs are case-insensitive and the service may spell one in upper case. The fixture ids above are all digits, so
+ // these carry letters for case to matter.
+ const root = 'abcdef01-2345-4abc-8def-0123456789ab';
+ const kid = 'fedcba98-7654-4cba-8fed-ba9876543210';
+ const other = 'c0ffee00-beef-4ace-8bad-f00ddeadbeef';
+ const U = (s) => s.toUpperCase();
+ const want = (r = root, c = kid) => ({ ...EXPECT, id: r, children: [{ ...EXPECT.children[0], id: c }] });
+ const res = (h, b, c) => ({ statusCode: 201, headers: { 'odata-entityid': at(h) }, body: JSON.stringify({ customapiid: b, CustomAPIRequestParameters: [child({ customapirequestparameterid: c })] }) });
+ const cases = [
+ ['all in lower case', want(), res(root, root, kid), 'acknowledged'],
+ ['the child answered in upper case', want(), res(root, root, U(kid)), 'acknowledged'],
+ ['the root answered in upper case, header and body', want(), res(U(root), U(root), kid), 'acknowledged'],
+ ['the expected child in upper case', want(root, U(kid)), res(root, root, kid), 'acknowledged'],
+ ['the expected root in upper case', want(U(root)), res(root, root, kid), 'acknowledged'],
+ ['another child, upper case', want(), res(root, root, U(other)), 'conflict'],
+ ['another child, lower case, expected in upper case', want(root, U(kid)), res(root, root, other), 'conflict'],
+ ['another root in the header, upper case', want(), res(U(other), root, kid), 'conflict'],
+ ['another root in the body, upper case', want(), res(root, U(other), kid), 'conflict'],
+ ];
+ for (const [name, w, r, outcome] of cases) assert.equal(answerOf(r, w).outcome, outcome, name);
+ assert.equal(answerOf(res(U(other), root, kid), want()).answeredId, other, 'the id that disagrees is reported in one spelling');
+});
+
+test('a deep insert whose answer names another child id is a conflict for every row it carried', async () => {
+ const h = harness({ answer: () => ({ statusCode: 201, headers: { 'odata-entityid': at() }, body: JSON.stringify({ customapiid: API, CustomAPIRequestParameters: [child({ customapirequestparameterid: OTHER })] }) }) });
+ const out = await runWithManagedCreateSet(h.set, () => h.client.post(URL_API, JSON.stringify(apiBody()), { headers: { Prefer: 'return=representation' } }));
+ assert.equal(h.sent.length, 1);
+ assert.deepEqual(out.facts.map((f) => [f.kind, f.outcome]), [['customApi', 'conflict'], ['customApiRequestParameter', 'conflict']]);
+});
+
+test('a row request that does not say which table and key its answer is read against, or where a child is found, is refused unsent', async () => {
+ const variants = [
+ (c) => ({ ...c, expectTable: undefined }),
+ (c) => ({ ...c, expectKey: 'not a field' }),
+ (c) => ({ ...c, rows: c.rows.map((r, i) => (i ? { ...r, answer: { at: 'CustomAPIRequestParameters', key: 'customapirequestparameterid', match: {} } } : r)) }),
+ ];
+ for (const change of variants) {
+ const h = harness();
+ const base = apiClassifier(h.token);
+ h.set.classify = (req) => { const c = base(req); return c && c.type === 'rows' ? change(c) : c; };
+ const before = JSON.stringify(diskOf(h.dir));
+ const out = await runWithManagedCreateSet(h.set, () => swallow(h.client.post(URL_API, JSON.stringify(apiBody()))));
+ assert.equal(out.localError.code, MISMATCH);
+ assert.equal(h.sent.length, 0);
+ assert.equal(JSON.stringify(diskOf(h.dir)), before);
+ }
+ const control = harness();
+ control.set.classify = apiClassifier(control.token);
+ const sent = await runWithManagedCreateSet(control.set, () => control.client.post(URL_API, JSON.stringify(apiBody())));
+ assert.deepEqual([sent.localError, control.sent.length], [null, 1], 'the same request with its descriptor whole is sent');
+});
+
+test('a request still unanswered when its set settles is an unknown fact; its late answer, or a second one, is not read', async () => {
+ let release;
+ const h = harness({ answer: () => new Promise((resolve) => { release = resolve; }) });
+ let pending;
+ const out = await runWithManagedCreateSet(h.set, async () => {
+ pending = swallow(h.client.post(URL_API, JSON.stringify(apiBody())));
+ while (h.sent.length === 0) await new Promise((resolve) => setImmediate(resolve));
+ return 'the SDK did not wait';
+ });
+ assert.equal(h.sent.length, 1);
+ assert.deepEqual(out.facts.map((f) => [f.kind, f.outcome, f.status, f.unanswered]), [['customApi', 'unknown', null, true], ['customApiRequestParameter', 'unknown', null, true]]);
+ release({ statusCode: 204, headers: { 'odata-entityid': at() }, body: '' });
+ await pending;
+ assert.equal(out.facts.length, 2);
+ const twice = harness();
+ const t = await runWithManagedCreateSet(twice.set, async () => {
+ const hd = twice.gate.screen({ method: 'POST', url: URL_API, body: JSON.stringify(apiBody()), headers: {} });
+ hd.dispatching();
+ hd.answered({ statusCode: 204, headers: { 'odata-entityid': at() }, body: '' });
+ hd.answered({ statusCode: 204, headers: { 'odata-entityid': at(OTHER) }, body: '' });
+ });
+ assert.deepEqual(t.facts.map((f) => f.outcome), ['acknowledged', 'acknowledged']);
+});
+
+test('inside a set, a refusal anywhere in the composed boundary is kept as the local failure, in either gate order', async () => {
+ const refusal = () => Object.assign(new Error('no'), { code: 'managed-workflow-effect-mismatch' });
+ const refusing = { screen: () => { throw refusal(); } };
+ for (const order of [(g) => [refusing, g], (g) => [g, refusing]]) {
+ const h = harness();
+ const out = await runWithManagedCreateSet(h.set, async () => {
+ try { composeWriteGates(...order(h.gate)).screen({ method: 'POST', url: URL_API, body: JSON.stringify(apiBody()), headers: {} }); } catch { /* the SDK swallowed it */ }
+ return 'saved';
+ });
+ assert.equal(out.value, 'saved');
+ assert.equal(out.localError && out.localError.code, 'managed-workflow-effect-mismatch');
+ }
+ const thrown = refusal();
+ const owner = { dispatching() { throw thrown; }, answered() {} };
+ const workflow = { screen: () => owner };
+ const out = await runWithManagedCreateSet(harness().set, async () => {
+ const hd = composeWriteGates(workflow).screen({ method: 'POST', url: `${ENV}/api/data/v9.2/workflows`, body: '{}' });
+ try { hd.dispatching(); } catch { /* the SDK swallowed it */ }
+ return 'saved';
+ });
+ assert.equal(out.localError, thrown, 'a handle that refuses at dispatch is latched too');
+ assert.equal(composeWriteGates(workflow).screen({ method: 'POST', url: `${ENV}/api/data/v9.2/workflows` }), owner, 'outside a set the handle is the gate\'s own');
+ assert.throws(() => composeWriteGates(refusing).screen({ method: 'POST', url: URL_API }), { code: 'managed-workflow-effect-mismatch' });
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/phase-diff.test.js b/plugins/model-apps/scripts/tests/phase-diff.test.js
index 404325dfe..1e7ec9bc9 100644
--- a/plugins/model-apps/scripts/tests/phase-diff.test.js
+++ b/plugins/model-apps/scripts/tests/phase-diff.test.js
@@ -39,6 +39,22 @@ test('diffPhases: a data-model change is reported under data-model (drives the f
assert.ok(!changed.includes('pages'), 'unrelated phases are not falsely flagged');
});
+test('diffPhases: a configuration declaration change (or its opt-in) is reported under data-model; absent on both sides is no change', () => {
+ const edits = {
+ configurationIdentity: 'stable-v1',
+ environmentVariables: [{ schemaName: 'new_Endpoint', displayName: 'Endpoint', type: 'String' }],
+ connectionReferences: [{ logicalName: 'new_sharedoffice', connectorId: '/providers/Microsoft.PowerApps/apis/shared_office365' }],
+ customApis: [{ uniqueName: 'new_Calc', displayName: 'Calc' }],
+ duplicateDetectionRules: [{ name: 'Same name', baseEntity: 'new_x', matchingEntity: 'new_x' }],
+ };
+ for (const [field, value] of Object.entries(edits)) {
+ const cur = { ...spec(), [field]: value };
+ assert.deepStrictEqual(diffPhases(cur, spec()), ['data-model'], `${field} added`);
+ assert.deepStrictEqual(diffPhases(spec(), cur), ['data-model'], `${field} removed`);
+ assert.deepStrictEqual(diffPhases(cur, { ...spec(), [field]: value }), [], `${field} unchanged`);
+ }
+});
+
test('diffPhases: app OR appShell change reports app-shell', () => {
const cur = spec();
cur.appShell.areas[0].label = 'Renamed';
diff --git a/plugins/model-apps/scripts/tests/teardown-model-app.test.js b/plugins/model-apps/scripts/tests/teardown-model-app.test.js
index 7ba7a7901..ad5cbb837 100644
--- a/plugins/model-apps/scripts/tests/teardown-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/teardown-model-app.test.js
@@ -156,6 +156,25 @@ test('such a spec is still refused before any teardown for any other problem, an
assert.strictEqual(sdk.calls.length, 0, 'no SDK calls on a bad spec');
});
+// A key a view or one of its filters does not take is refused by the build and the lint the same way (#827), and an earlier release accepted
+// and ignored it: under the structural profile it is a warning, so an app built from such a spec is still torn down, behind the same authorization.
+const VIEW_KEY_TYPO = "view 'Active Tickets': unknown key 'filter' — did you mean 'filters'?; the build does not read it, so it is refused rather than built without it (allowed: entity, name, description, columns, sort, filters, activeOnly, reconcile, key, viewId, linkEntities)";
+
+test('a spec whose view carries a key it does not take is still torn down: the dry run lists the same plan, and apply deletes', async () => {
+ const spec = JSON.parse(JSON.stringify(desk));
+ spec.views.find((v) => v.name === 'Active Tickets').filter = [{ attr: 'new_status', op: 'eq', value: 1 }];
+ const structural = validateAppSpec(spec, { profile: 'structural' });
+ assert.deepStrictEqual([structural.ok, structural.errors, structural.warnings], [true, [], [VIEW_KEY_TYPO]], 'the finding is a warning there');
+ const r = await teardownModelApp(spec, { apply: false }, { sdk: { queryRecords: async () => [] } });
+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
+ const plain = await teardownModelApp(desk, { apply: false }, { sdk: { queryRecords: async () => [] } });
+ assert.deepStrictEqual(r.plan, plain.plan, 'the plan of the same spec without the key');
+ const sdk = presentSdk();
+ const applied = await teardownModelApp(spec, { apply: true, allowDestructive: true }, { sdk });
+ assert.strictEqual(applied.ok, true, JSON.stringify(applied.errors));
+ assert.ok(sdk.calls.some((c) => c.method === 'deleteAppCascade'), 'app deleted');
+});
+
// A key a table's `primaryAttribute` does not take is refused the same way, and an earlier release accepted and ignored it just the
// same: under the structural profile it is a warning, so such an app is still torn down, behind the same authorization.
const PRIMARY_ATTRIBUTE_TYPO = "entity new_ticket: unknown key 'maxlength' on primaryAttribute — did you mean 'maxLength'? (allowed: schemaName, displayName, autoNumberFormat, required, maxLength)";
diff --git a/plugins/model-apps/scripts/tests/verify-model-app.test.js b/plugins/model-apps/scripts/tests/verify-model-app.test.js
index 15f897679..8313ecc63 100644
--- a/plugins/model-apps/scripts/tests/verify-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/verify-model-app.test.js
@@ -1005,6 +1005,22 @@ test('verify CLI still verifies the deployment of a table whose primaryAttribute
assert.deepStrictEqual(result.warnings, [PRIMARY_ATTRIBUTE_TYPO]);
});
+// --- a view that carries a key it does not take ---------------------------------------------------------------------------------------
+// The build and the lint refuse a key a `views[]` entry does not take (#827); a release before that check accepted one and built the view without
+// that part. Verification passes viewKeys: 'warn': a warning that names the key and the key it most likely meant, and the verdict is the deployment's.
+const VIEW_KEY_TYPO = "view 'Red tickets': unknown key 'filter' — did you mean 'filters'?; the build does not read it, so it is refused rather than built without it (allowed: entity, name, description, columns, sort, filters, activeOnly, reconcile, key, viewId, linkEntities)";
+
+test('verify CLI still verifies the deployment of a view that carries a key it does not take — and warns, naming the key', async () => {
+ const spec = { ...appSpec({ columns: [column({ type: 'Text' })] }), views: [{ entity: 'new_ticket', name: 'Red tickets', columns: ['new_name'], filter: [{ attr: 'new_ref', op: 'eq', value: 'red' }] }] };
+ const { reads, emitted, stderr } = await verifyOlderSpec(spec);
+ const result = JSON.parse(JSON.stringify(emitted.payload));
+ assert.ok(Number.isInteger(result.total) && result.total > 0 && Array.isArray(result.missing), `a verdict, not a refusal: ${JSON.stringify(result)}`);
+ assert.ok(reads.includes('columns new_ticket'), `the deployed columns were read: ${JSON.stringify(reads)}`);
+ assert.ok(stderr.includes(`WARNING: ${VIEW_KEY_TYPO}\n`), stderr);
+ assert.ok(result.warnings.includes(VIEW_KEY_TYPO), JSON.stringify(result.warnings));
+ assert.ok(!result.errors.some((e) => /unknown key/.test(e)), JSON.stringify(result.errors));
+});
+
// --- the result JSON carries what stderr warns -----------------------------------------------------------------------------------------
// A person reads the `WARNING:` lines verify prints, but a caller that reads only the JSON result — a skill, a pipeline — lost them. The result's optional
// `warnings` array holds the same messages, without the prefix and in the order they were printed, and is left out when there is none, as `unverified` is.
diff --git a/plugins/model-apps/scripts/tests/verify-spec.test.js b/plugins/model-apps/scripts/tests/verify-spec.test.js
index 5dae7acb2..d6e267022 100644
--- a/plugins/model-apps/scripts/tests/verify-spec.test.js
+++ b/plugins/model-apps/scripts/tests/verify-spec.test.js
@@ -3771,6 +3771,22 @@ test('verifySpec: configuration items pass, drift with code and fields, and an u
assert.strictEqual(r.ok, false, 'a drift fails the verify');
});
+test('verifySpec: the configuration getter is handed the workspace binding store, and a protected item still being settled is unverified', async () => {
+ let seen;
+ const managedManifest = { revision: 1, groups: [], pending: [{ family: 'customApi', key: 'contoso_calc', code: 'managed-settlement-pending' }], invalid: [] };
+ const read = otherReadsNull({ configuration: async (s, b, m) => { seen = m; return [
+ { kind: 'environmentVariable', key: 'contoso_ApiBase', name: 'definition', ok: false, code: 'configuration-row-not-found' },
+ { kind: 'customApi', key: 'contoso_Calc', name: 'definition', ok: false, code: 'managed-settlement-pending' },
+ ]; } });
+ const r = await verifySpec({ ...CONFIG_SPEC, configurationIdentity: 'stable-v1' }, read, { managedManifest });
+ assert.strictEqual(seen, managedManifest);
+ assert.deepStrictEqual(configChecks(r), [
+ { kind: 'configuration', name: 'environmentVariable contoso_ApiBase: definition', present: false, detail: 'configuration-row-not-found' },
+ ]);
+ assert.ok(r.unverified.includes('configuration:customApi contoso_Calc: definition (managed-settlement-pending)'), r.unverified.join('\n'));
+ assert.strictEqual(r.ok, false);
+});
+
test('verifySpec: a reader without the configuration getter reports the configuration items as unverified, not as passing', async () => {
const r = await verifySpec(CONFIG_SPEC, otherReadsNull({}), {});
assert.deepStrictEqual(configChecks(r), []);
diff --git a/plugins/model-apps/scripts/tests/view-key-refusal.test.js b/plugins/model-apps/scripts/tests/view-key-refusal.test.js
new file mode 100644
index 000000000..a395944e5
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/view-key-refusal.test.js
@@ -0,0 +1,92 @@
+'use strict';
+// A view written with a key the build does not read (`filter` for `filters`, #827) is refused by every build, and a refusal sends NOTHING:
+// * over the REAL vendored SDK, the plugin's own HTTP client and the stateful fake Dataverse (helpers/fake-lifecycle-org.js), counted at the
+// transport — every request the build sends, not only the ones a double chooses to log;
+// * through the command, where a --changed-only apply could otherwise end in a no-op that certifies the spec without building it.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');
+const { createLifecycleHarness } = require('./helpers/lifecycle-harness.js');
+const { appFolder, command, settle, ENV } = require('./helpers/build-command-harness.js');
+const { migrateAppSpec } = require('../lib/app-spec.js');
+const { appUniqueName } = require('../lib/sdk-build.js');
+const { annotateContentHashes } = require('../lib/content-hash.js');
+const flow = require('../lib/changed-only-flow.js');
+const store = require('../lib/apply-snapshot-store.js');
+
+const viewSpec = (key) => ({
+ schemaVersion: 2,
+ solution: { uniqueName: 'ContosoViewKeys', publisherPrefix: 'contoso' },
+ app: { name: 'View Keys' },
+ entities: [{ schemaName: 'contoso_order', displayName: 'Order', pluralName: 'Orders', primaryAttribute: { schemaName: 'contoso_name' }, columns: [] }],
+ views: [{ entity: 'contoso_order', name: 'Red orders', columns: ['contoso_name'], [key]: [{ attr: 'contoso_name', op: 'eq', value: 'red' }] }],
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Orders', subAreas: [{ entity: 'contoso_order', title: 'Orders' }] }] }] },
+});
+
+test('over the real SDK, a build of a view written with `filter` sends no request at all, and the same view written with `filters` is written with its condition', async () => {
+ for (const [key, built] of [['filter', false], ['filters', true]]) {
+ const root = makeTempDir('view-key-refusal-');
+ const org = createLifecycleOrg();
+ const harness = createLifecycleHarness(org, root);
+ const { result } = await harness.build(viewSpec(key), { publish: false, sampleData: false, verify: false });
+ const views = org.find('savedqueries', (row) => row.name === 'Red orders');
+ if (!built) {
+ assert.equal(result.ok, false, key);
+ assert.ok(result.errors.some((e) => /^view 'Red orders': unknown key 'filter' — did you mean 'filters'\?/.test(e)), JSON.stringify(result.errors));
+ assert.equal(org.requests.length, 0, `a refused build sent ${org.requests.map((r) => `${r.method} ${r.path}`).join(', ')}`);
+ assert.equal(views.length, 0);
+ } else {
+ assert.equal(result.ok, true, JSON.stringify(result.errors));
+ assert.ok(org.requests.some((r) => r.method !== 'GET'), 'the control spec is written');
+ assert.equal(views.length, 1);
+ assert.match(views[0].fetchxml, /attribute=["']contoso_name["']/);
+ assert.match(views[0].fetchxml, /value=["']red["']/);
+ }
+ }
+});
+
+// What the command does with an app whose last build is recorded as an ELIGIBLE baseline: the spec the earlier release built, now carrying the
+// key that release dropped. The baseline is what a --changed-only run trusts to skip the build, so an unchanged spec would be a no-op.
+function eligibleBaseline(spec) {
+ const folder = appFolder(spec);
+ const live = { orgId: 'org-contoso', envUrl: ENV, appUniqueName: appUniqueName(spec), appId: 'app-contoso' };
+ fs.mkdirSync(folder.workspaceDir, { recursive: true });
+ const envelope = flow.assembleBaselineSnapshot({ annotatedSpec: annotateContentHashes(migrateAppSpec(spec), () => null), created: { app: live.appId }, live, prior: null });
+ assert.equal(envelope.eligible, true, 'the baseline is one a no-op may trust');
+ store.writeSnapshotAtomic(folder.workspaceDir, envelope);
+ return { folder, live };
+}
+
+test('a --changed-only apply of an unchanged spec holding `filter` is refused as a build refuses it: exit 1, the error once, nothing sent, no baseline written', async () => {
+ const { folder, live } = eligibleBaseline(viewSpec('filter'));
+ const before = fs.readFileSync(store.snapshotPath(folder.workspaceDir), 'utf8');
+ const run = command(folder, { argv: ['--changed-only'], live });
+ const outcome = await settle(run);
+ const printed = run.authCli.stdoutText();
+ assert.equal(outcome.exitCode, 1, printed);
+ assert.equal(run.printed.ok, false);
+ assert.equal(printed.split("unknown key 'filter'").length - 1, 1, `the finding is printed once: ${printed}`);
+ assert.match(printed, /view 'Red orders': unknown key 'filter' — did you mean 'filters'\?/);
+ assert.equal(JSON.parse(printed).changedOnly, undefined, 'the refusal is the build\'s own, with no changed-only decision');
+ assert.deepEqual(run.calls.filter((c) => c === 'engine' || c === 'baseline'), [], 'nothing was built and no baseline was written');
+ assert.equal(fs.readFileSync(store.snapshotPath(folder.workspaceDir), 'utf8'), before, 'the recorded baseline is as it was');
+});
+
+test('a --changed-only apply of the same spec written with `filters` is still a no-op, and with no baseline it is still the full build', async () => {
+ const { folder, live } = eligibleBaseline(viewSpec('filters'));
+ const noop = command(folder, { argv: ['--changed-only'], live });
+ const outcome = await settle(noop);
+ assert.equal(outcome.exitCode, 0, noop.authCli.stdoutText());
+ const payload = JSON.parse(noop.authCli.stdoutText());
+ assert.equal(payload.noop, true);
+ assert.equal(payload.changedOnly.decision, 'noop');
+ assert.equal(noop.calls.includes('engine'), false, 'nothing was built');
+
+ const fresh = appFolder(viewSpec('filters'));
+ const full = command(fresh, { argv: ['--changed-only'], live });
+ assert.equal((await settle(full)).exitCode, 0, full.authCli.stdoutText());
+ assert.equal(JSON.parse(full.authCli.stdoutText()).changedOnly.decision, 'full');
+ assert.equal(full.calls.filter((c) => c === 'engine').length, 1, 'the full build ran once');
+});
diff --git a/plugins/model-apps/scripts/verify-model-app.js b/plugins/model-apps/scripts/verify-model-app.js
index 23930425e..1a7e43637 100644
--- a/plugins/model-apps/scripts/verify-model-app.js
+++ b/plugins/model-apps/scripts/verify-model-app.js
@@ -241,9 +241,15 @@ function readerFor(sdk, appUnique, opts) {
// The configuration kinds (lib/configuration-artifacts.js verifyConfiguration), read through this reader's SDK: each declared item's
// definition, its binding when the build was given one (--deployment-settings), a required variable's value, a Custom API's
// implementation, a rule's publication and the solution's version. Reads only.
- configuration: async (spec, bindings) => {
+ // Under `configurationIdentity: "stable-v1"` the workspace's binding store (`managedManifest`, readVerifyManifest) names the one
+ // row each item is checked at (lib/configuration-protected.js protectedVerifyPort): never a name lookup, never a write.
+ configuration: async (spec, bindings, managedManifest) => {
const C = require('./lib/configuration-artifacts.js');
- return C.verifyConfiguration(spec, C.configurationContext({ sdk, bindings, solutionUniqueName: spec && spec.solution && spec.solution.uniqueName }));
+ const solutionUniqueName = spec && spec.solution && spec.solution.uniqueName;
+ const creates = spec && spec.configurationIdentity === 'stable-v1'
+ ? require('./lib/configuration-protected.js').protectedVerifyPort({ spec, manifest: managedManifest, dataverse: sdk.dataverse, solution: solutionUniqueName, bindings })
+ : undefined;
+ return C.verifyConfiguration(spec, C.configurationContext({ sdk, bindings, solutionUniqueName, creates }));
},
findTable: async (logical) => {
const l = String(logical).toLowerCase();
@@ -805,9 +811,11 @@ async function main() {
// verification only reads that deployment. Every other finding about the entry stays an error.
// `primaryAttributeKeys: 'warn'` is the same again for a key a table's `primaryAttribute` does not take: an earlier release accepted and
// ignored it, and the table was built without it.
+ // `viewKeys: 'warn'` is the same for a key a `views[]` entry or one of its filters does not take: the build refuses one, because it would
+ // drop it and build the view without that part, but an earlier release accepted it — and verification only reads that deployment.
// `declaredKeyCollisions: 'warn'` is the same for two declared views (or two declared charts) on one table with one name: a build refuses them,
// because one --authorize adopt:/overwrite: approval would name both, but verification takes no approval and only reads what was deployed.
- const v = validateAppSpec(spec, { profile: 'deploy', relationshipCollisions: 'warn', columnValues: 'warn', fieldOptionKeys: 'warn', primaryAttributeKeys: 'warn', declaredKeyCollisions: 'warn' });
+ const v = validateAppSpec(spec, { profile: 'deploy', relationshipCollisions: 'warn', columnValues: 'warn', fieldOptionKeys: 'warn', primaryAttributeKeys: 'warn', viewKeys: 'warn', declaredKeyCollisions: 'warn' });
// A warning is printed for a person and kept for the result JSON in one step, so the two cannot differ: a caller that reads only the JSON must not
// lose what stderr says. The spec's are found before it is judged, so a spec that is refused reports the warnings it also has.
const warnings = [];